home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / text / edit / vim60src.lha / Vim / vim60 / src / fileio.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-09-20  |  183.3 KB  |  7,574 lines

  1. /* vi:set ts=8 sts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved    by Bram Moolenaar
  4.  *
  5.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  6.  * Do ":help credits" in Vim to see a list of people who contributed.
  7.  * See README.txt for an overview of the Vim source code.
  8.  */
  9.  
  10. /*
  11.  * fileio.c: read from and write to a file
  12.  */
  13.  
  14. #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
  15. # include <io.h>    /* for lseek(), must be before vim.h */
  16. #endif
  17.  
  18. #if defined __EMX__
  19. # include <io.h>    /* for mktemp(), CJW 1997-12-03 */
  20. #endif
  21.  
  22. #include "vim.h"
  23.  
  24. #ifdef HAVE_FCNTL_H
  25. # include <fcntl.h>
  26. #endif
  27.  
  28. #ifdef LATTICE
  29. # include <proto/dos.h>        /* for Lock() and UnLock() */
  30. #endif
  31.  
  32. #define BUFSIZE        8192    /* size of normal write buffer */
  33. #define SMBUFSIZE    256    /* size of emergency write buffer */
  34.  
  35. #ifdef FEAT_CRYPT
  36. # define CRYPT_MAGIC        "VimCrypt~01!"    /* "01" is the version nr */
  37. # define CRYPT_MAGIC_LEN    12        /* must be multiple of 4! */
  38. #endif
  39.  
  40. /* Is there any system that doesn't have access()? */
  41. #ifndef MACOS_CLASSIC /* Not available on MacOS 9 */
  42. # define USE_MCH_ACCESS
  43. #endif
  44.  
  45. #ifdef FEAT_MBYTE
  46. static char_u *next_fenc __ARGS((char_u **pp));
  47. # ifdef FEAT_EVAL
  48. static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
  49. # endif
  50. #endif
  51. #ifdef FEAT_VIMINFO
  52. static void check_marks_read __ARGS((void));
  53. #endif
  54. #ifdef FEAT_CRYPT
  55. static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, long *filesizep, int newfile));
  56. #endif
  57. #ifdef UNIX
  58. static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
  59. #endif
  60. static void msg_add_fname __ARGS((buf_T *, char_u *));
  61. static int msg_add_fileformat __ARGS((int eol_type));
  62. static void msg_add_lines __ARGS((int, long, long));
  63. static void msg_add_eol __ARGS((void));
  64. static int check_mtime __ARGS((buf_T *buf, struct stat *s));
  65. static int time_differs __ARGS((long t1, long t2));
  66. #ifdef FEAT_AUTOCMD
  67. static int apply_autocmds_exarg __ARGS((EVENT_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap));
  68. #endif
  69.  
  70. #if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
  71. # define HAS_BW_FLAGS
  72. # define FIO_LATIN1    0x01    /* convert Latin1 */
  73. # define FIO_UTF8    0x02    /* convert UTF-8 */
  74. # define FIO_UCS2    0x04    /* convert UCS-2 */
  75. # define FIO_UCS4    0x08    /* convert UCS-4 */
  76. # define FIO_UTF16    0x10    /* convert UTF-16 */
  77. # define FIO_ENDIAN_L    0x80    /* little endian */
  78. # define FIO_ENCRYPTED    0x1000    /* encrypt written bytes */
  79. # define FIO_NOCONVERT    0x2000    /* skip encoding conversion */
  80. # define FIO_UCSBOM    0x4000    /* check for BOM at start of file */
  81. # define FIO_ALL    -1    /* allow all formats */
  82. #endif
  83.  
  84. /* When converting, a read() or write() may leave some bytes to be converted
  85.  * for the next call.  The value is guessed... */
  86. #define CONV_RESTLEN 30
  87.  
  88. /* We have to guess how much a sequence of bytes may expand when converting
  89.  * with iconv() to be able to allocate a buffer. */
  90. #define ICONV_MULT 8
  91.  
  92. /*
  93.  * Structure to pass arguments from buf_write() to buf_write_bytes().
  94.  */
  95. struct bw_info
  96. {
  97.     int        bw_fd;        /* file descriptor */
  98.     char_u    *bw_buf;    /* buffer with data to be written */
  99.     int        bw_len;    /* lenght of data */
  100. #ifdef HAS_BW_FLAGS
  101.     int        bw_flags;    /* FIO_ flags */
  102. #endif
  103. #ifdef FEAT_MBYTE
  104.     char_u    bw_rest[CONV_RESTLEN]; /* not converted bytes */
  105.     int        bw_restlen;    /* nr of bytes in bw_rest[] */
  106.     int        bw_first;    /* first write call */
  107.     char_u    *bw_conv_buf;    /* buffer for writing converted chars */
  108.     int        bw_conv_buflen; /* size of bw_conv_buf */
  109.     int        bw_conv_error;    /* set for conversion error */
  110. # ifdef USE_ICONV
  111.     iconv_t    bw_iconv_fd;    /* descriptor for iconv() or -1 */
  112. # endif
  113. #endif
  114. };
  115.  
  116. static int  buf_write_bytes __ARGS((struct bw_info *ip));
  117.  
  118. #ifdef FEAT_MBYTE
  119. static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
  120. static int same_encoding __ARGS((char_u *a, char_u *b));
  121. static int get_fio_flags __ARGS((char_u *ptr));
  122. static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
  123. static int make_bom __ARGS((char_u *buf, char_u *name));
  124. #endif
  125.  
  126. static linenr_T    write_no_eol_lnum = 0;    /* non-zero lnum when last line of
  127.                        next binary write should not have
  128.                        an end-of-line */
  129.  
  130.     void
  131. filemess(buf, name, s, attr)
  132.     buf_T    *buf;
  133.     char_u    *name;
  134.     char_u    *s;
  135.     int        attr;
  136. {
  137.     int        msg_scroll_save;
  138.  
  139.     if (msg_silent != 0)
  140.     return;
  141.     msg_add_fname(buf, name);        /* put file name in IObuff with quotes */
  142.     /* If it's extremely long, truncate it. */
  143.     if (STRLEN(IObuff) > IOSIZE - 80)
  144.     IObuff[IOSIZE - 80] = NUL;
  145.     STRCAT(IObuff, s);
  146.     /*
  147.      * For the first message may have to start a new line.
  148.      * For further ones overwrite the previous one, reset msg_scroll before
  149.      * calling filemess().
  150.      */
  151.     msg_scroll_save = msg_scroll;
  152.     if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
  153.     msg_scroll = FALSE;
  154.     if (!msg_scroll)    /* wait a bit when overwriting an error msg */
  155.     check_for_delay(FALSE);
  156.     msg_start();
  157.     msg_scroll = msg_scroll_save;
  158.     msg_scrolled_ign = TRUE;
  159.     /* may truncate the message to avoid a hit-return prompt */
  160.     msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
  161.     msg_clr_eos();
  162.     out_flush();
  163.     msg_scrolled_ign = FALSE;
  164. }
  165.  
  166. /*
  167.  * Read lines from file "fname" into the buffer after line "from".
  168.  *
  169.  * 1. We allocate blocks with lalloc, as big as possible.
  170.  * 2. Each block is filled with characters from the file with a single read().
  171.  * 3. The lines are inserted in the buffer with ml_append().
  172.  *
  173.  * (caller must check that fname != NULL, unless READ_STDIN is used)
  174.  *
  175.  * "lines_to_skip" is the number of lines that must be skipped
  176.  * "lines_to_read" is the number of lines that are appended
  177.  * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
  178.  *
  179.  * flags:
  180.  * READ_NEW    starting to edit a new buffer
  181.  * READ_FILTER    reading filter output
  182.  * READ_STDIN    read from stdin instead of a file
  183.  * READ_BUFFER    read from curbuf instead of a file (converting after reading
  184.  *        stdin)
  185.  * READ_DUMMY    read into a dummy buffer (to check if file contents changed)
  186.  *
  187.  * return FAIL for failure, OK otherwise
  188.  */
  189.     int
  190. readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
  191.     char_u    *fname;
  192.     char_u    *sfname;
  193.     linenr_T    from;
  194.     linenr_T    lines_to_skip;
  195.     linenr_T    lines_to_read;
  196.     exarg_T    *eap;            /* can be NULL! */
  197.     int        flags;
  198. {
  199.     int        fd = 0;
  200.     int        newfile = (flags & READ_NEW);
  201.     int        check_readonly;
  202.     int        filtering = (flags & READ_FILTER);
  203.     int        read_stdin = (flags & READ_STDIN);
  204.     int        read_buffer = (flags & READ_BUFFER);
  205.     linenr_T    read_buf_lnum = 1;    /* next line to read from curbuf */
  206.     colnr_T    read_buf_col = 0;    /* next char to read from this line */
  207.     char_u    c;
  208.     linenr_T    lnum = from;
  209.     char_u    *ptr = NULL;        /* pointer into read buffer */
  210.     char_u    *buffer = NULL;        /* read buffer */
  211.     char_u    *new_buffer = NULL;    /* init to shut up gcc */
  212.     char_u    *line_start = NULL;    /* init to shut up gcc */
  213.     int        wasempty;        /* buffer was empty before reading */
  214.     colnr_T    len;
  215.     long    size = 0;
  216.     char_u    *p;
  217.     long    filesize = 0;
  218.     int        skip_read = FALSE;
  219. #ifdef FEAT_CRYPT
  220.     char_u    *cryptkey = NULL;
  221. #endif
  222.     int        split = 0;        /* number of split lines */
  223. #define UNKNOWN     0x0fffffff        /* file size is unknown */
  224.     linenr_T    linecnt;
  225.     int        error = FALSE;        /* errors encountered */
  226.     int        ff_error = EOL_UNKNOWN; /* file format with errors */
  227.     long    linerest = 0;        /* remaining chars in line */
  228. #ifdef UNIX
  229.     int        perm = 0;
  230. #else
  231.     int        perm;
  232. #endif
  233.     int        fileformat = 0;        /* end-of-line format */
  234.     int        keep_fileformat = FALSE;
  235.     struct stat    st;
  236.     int        file_readonly;
  237.     linenr_T    skip_count = 0;
  238.     linenr_T    read_count = 0;
  239.     int        msg_save = msg_scroll;
  240.     linenr_T    read_no_eol_lnum = 0;   /* non-zero lnum when last line of
  241.                      * last read was missing the eol */
  242.     int        try_mac = (vim_strchr(p_ffs, 'm') != NULL);
  243.     int        try_dos = (vim_strchr(p_ffs, 'd') != NULL);
  244.     int        try_unix = (vim_strchr(p_ffs, 'x') != NULL);
  245.     int        file_rewind = FALSE;
  246. #ifdef FEAT_MBYTE
  247.     int        can_retry;
  248.     int        conv_error = FALSE;    /* conversion error detected */
  249.     char_u    *tmpname = NULL;    /* name of 'charconvert' output file */
  250.     int        fio_flags = 0;
  251.     char_u    *fenc;            /* fileencoding to use */
  252.     int        fenc_alloced;        /* fenc_next is in allocated memory */
  253.     char_u    *fenc_next = NULL;    /* next item in 'fencs' or NULL */
  254.     int        advance_fenc = FALSE;
  255.     long    real_size = 0;
  256. # ifdef USE_ICONV
  257.     iconv_t    iconv_fd = (iconv_t)-1;    /* descriptor for iconv() or -1 */
  258. #  ifdef FEAT_EVAL
  259.     int        did_iconv = FALSE;    /* TRUE when iconv() failed and trying
  260.                        'charconvert' next */
  261. #  endif
  262. # endif
  263.     int        converted = FALSE;    /* TRUE if conversion done */
  264.     int        notconverted = FALSE;    /* TRUE if conversion wanted but it
  265.                        wasn't possible */
  266.     char_u    conv_rest[CONV_RESTLEN];
  267.     int        conv_restlen = 0;    /* nr of bytes in conv_rest[] */
  268. #endif
  269.  
  270. #ifdef FEAT_AUTOCMD
  271.     write_no_eol_lnum = 0;    /* in case it was set by the previous read */
  272. #endif
  273.  
  274.     /*
  275.      * If there is no file name yet, use the one for the read file.
  276.      * BF_NOTEDITED is set to reflect this.
  277.      * Don't do this for a read from a filter.
  278.      * Only do this when 'cpoptions' contains the 'f' flag.
  279.      */
  280.     if (curbuf->b_ffname == NULL
  281.         && !filtering
  282.         && fname != NULL
  283.         && vim_strchr(p_cpo, CPO_FNAMER) != NULL
  284.         && !(flags & READ_DUMMY))
  285.     {
  286.     if (setfname(fname, sfname, FALSE) == OK)
  287.         curbuf->b_flags |= BF_NOTEDITED;
  288.     }
  289.  
  290.     /*
  291.      * For Unix: Use the short file name whenever possible.
  292.      * Avoids problems with networks and when directory names are changed.
  293.      * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
  294.      * another directory, which we don't detect.
  295.      */
  296.     if (sfname == NULL)
  297.     sfname = fname;
  298. #if defined(UNIX) || defined(__EMX__)
  299.     fname = sfname;
  300. #endif
  301.  
  302. #ifdef FEAT_AUTOCMD
  303.     /*
  304.      * The BufReadCmd and FileReadCmd events intercept the reading process by
  305.      * executing the associated commands instead.
  306.      */
  307.     if (!filtering && !read_stdin && !read_buffer)
  308.     {
  309.     pos_T        pos;
  310.  
  311.     pos = curbuf->b_op_start;
  312.  
  313.     /* Set '[ mark to the line above where the lines go (line 1 if zero). */
  314.     curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
  315.     curbuf->b_op_start.col = 0;
  316.  
  317.     if (newfile)
  318.     {
  319.         if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
  320.                               FALSE, curbuf, eap))
  321.         return OK;
  322.     }
  323.     else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
  324.                                 FALSE, NULL, eap))
  325.         return OK;
  326.  
  327.     curbuf->b_op_start = pos;
  328.     }
  329. #endif
  330.  
  331.     if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
  332.     msg_scroll = FALSE;    /* overwrite previous file message */
  333.     else
  334.     msg_scroll = TRUE;    /* don't overwrite previous file message */
  335.  
  336.     /*
  337.      * If the name ends in a path separator, we can't open it.  Check here,
  338.      * because reading the file may actually work, but then creating the swap
  339.      * file may destroy it!  Reported on MS-DOS and Win 95.
  340.      * If the name is too long we might crash further on, quit here.
  341.      */
  342.     if (fname != NULL
  343.         && *fname != NUL
  344.         && (vim_ispathsep(*(fname + STRLEN(fname) - 1))
  345.         || STRLEN(fname) >= MAXPATHL))
  346.     {
  347.     filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
  348.     msg_end();
  349.     msg_scroll = msg_save;
  350.     return FAIL;
  351.     }
  352.  
  353. #ifdef UNIX
  354.     /*
  355.      * On Unix it is possible to read a directory, so we have to
  356.      * check for it before the mch_open().
  357.      */
  358.     if (!read_stdin && !read_buffer)
  359.     {
  360.     perm = mch_getperm(fname);
  361.     if (perm >= 0 && !S_ISREG(perm)            /* not a regular file ... */
  362. # ifdef S_ISFIFO
  363.               && !S_ISFIFO(perm)        /* ... or fifo */
  364. # endif
  365. # ifdef S_ISSOCK
  366.               && !S_ISSOCK(perm)        /* ... or socket */
  367. # endif
  368.                         )
  369.     {
  370.         if (S_ISDIR(perm))
  371.         filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
  372.         else
  373.         filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
  374.         msg_end();
  375.         msg_scroll = msg_save;
  376.         return FAIL;
  377.     }
  378.     }
  379. #endif
  380.  
  381.     /* set default 'fileformat' */
  382.     if (newfile)
  383.     {
  384.     if (eap != NULL && eap->force_ff != 0)
  385.         set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
  386.     else if (*p_ffs != NUL)
  387.         set_fileformat(default_fileformat(), OPT_LOCAL);
  388.     }
  389.  
  390.     /*
  391.      * When opening a new file we take the readonly flag from the file.
  392.      * Default is r/w, can be set to r/o below.
  393.      * Don't reset it when in readonly mode
  394.      * Only set/reset b_p_ro when BF_CHECK_RO is set.
  395.      */
  396.     check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
  397.     if (check_readonly && !readonlymode)    /* default: set file not readonly */
  398.     curbuf->b_p_ro = FALSE;
  399.  
  400.     if (newfile && !read_stdin && !read_buffer)
  401.     {
  402.     /* Remember time of file.
  403.      * For RISCOS, also remember the filetype.
  404.      */
  405.     if (mch_stat((char *)fname, &st) >= 0)
  406.     {
  407.         buf_store_time(curbuf, &st, fname);
  408.         curbuf->b_mtime_read = curbuf->b_mtime;
  409.  
  410. #if defined(RISCOS) && defined(FEAT_OSFILETYPE)
  411.         /* Read the filetype into the buffer local filetype option. */
  412.         mch_read_filetype(fname);
  413. #endif
  414. #ifdef UNIX
  415.         /*
  416.          * Set the protection bits of the swap file equal to the original
  417.          * file. This makes it possible for others to read the name of the
  418.          * original file from the swapfile.
  419.          */
  420.         if (curbuf->b_ml.ml_mfp->mf_fname != NULL)
  421.         (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname,
  422.                       (long)((st.st_mode & 0777) | 0600));
  423. #endif
  424. #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
  425.         /* Get the FSSpec on MacOS
  426.          * TODO: Update it properly when the buffer name changes
  427.          */
  428.         (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
  429. #endif
  430. #ifdef VMS
  431.         curbuf->b_fab_rfm = st.st_fab_rfm;
  432. #endif
  433.     }
  434.     else
  435.     {
  436.         curbuf->b_mtime = 0;
  437.         curbuf->b_mtime_read = 0;
  438.         curbuf->b_orig_size = 0;
  439.         curbuf->b_orig_mode = 0;
  440.     }
  441.  
  442.     /* Reset the "new file" flag.  It will be set again below when the
  443.      * file doesn't exist. */
  444.     curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
  445.     }
  446.  
  447. /*
  448.  * for UNIX: check readonly with perm and mch_access()
  449.  * for RISCOS: same as Unix, otherwise file gets re-datestamped!
  450.  * for MSDOS and Amiga: check readonly by trying to open the file for writing
  451.  */
  452.     file_readonly = FALSE;
  453.     if (read_stdin)
  454.     {
  455. #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
  456.     /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
  457.     setmode(0, O_BINARY);
  458. #endif
  459.     }
  460.     else if (!read_buffer)
  461.     {
  462. #ifdef USE_MCH_ACCESS
  463.     if (
  464. # ifdef UNIX
  465.         !(perm & 0222) ||
  466. # endif
  467.                 mch_access((char *)fname, W_OK))
  468.         file_readonly = TRUE;
  469.     fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
  470. #else
  471.     if (!newfile
  472.         || readonlymode
  473.         || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
  474.     {
  475.         file_readonly = TRUE;
  476.         /* try to open ro */
  477.         fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
  478.     }
  479. #endif
  480.     }
  481.  
  482.     if (fd < 0)                /* cannot open at all */
  483.     {
  484. #ifndef UNIX
  485.     int    isdir_f;
  486. #endif
  487.     msg_scroll = msg_save;
  488. #ifndef UNIX
  489.     /*
  490.      * On MSDOS and Amiga we can't open a directory, check here.
  491.      */
  492.     isdir_f = (mch_isdir(fname));
  493.     perm = mch_getperm(fname);  /* check if the file exists */
  494.     if (isdir_f)
  495.         filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
  496.     else
  497. #endif
  498.         if (newfile)
  499.         {
  500.         if (perm < 0)
  501.         {
  502.             /*
  503.              * Set the 'new-file' flag, so that when the file has
  504.              * been created by someone else, a ":w" will complain.
  505.              */
  506.             curbuf->b_flags |= BF_NEW;
  507.  
  508.             /* Create a swap file now, so that other Vims are warned
  509.              * that we are editing this file.  Don't do this for a
  510.              * "nofile" or "nowrite" buffer type. */
  511. #ifdef FEAT_QUICKFIX
  512.             if (!bt_dontwrite(curbuf))
  513. #endif
  514.             check_need_swap(newfile);
  515.             filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
  516. #ifdef FEAT_VIMINFO
  517.             /* Even though this is a new file, it might have been
  518.              * edited before and deleted.  Get the old marks. */
  519.             check_marks_read();
  520. #endif
  521. #ifdef FEAT_AUTOCMD
  522.             apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
  523.                               FALSE, curbuf, eap);
  524. #endif
  525.             /* remember the current fileformat */
  526.             save_file_ff(curbuf);
  527.  
  528.             return OK;        /* a new file is not an error */
  529.         }
  530.         else
  531.             filemess(curbuf, sfname,
  532.                       (char_u *)_("[Permission Denied]"), 0);
  533.         }
  534.  
  535.     return FAIL;
  536.     }
  537.  
  538.     /*
  539.      * Only set the 'ro' flag for readonly files the first time they are
  540.      * loaded.    Help files always get readonly mode
  541.      */
  542.     if ((check_readonly && file_readonly) || curbuf->b_help)
  543.     curbuf->b_p_ro = TRUE;
  544.  
  545.     if (newfile)
  546.     {
  547.     curbuf->b_p_eol = TRUE;
  548. #ifdef FEAT_MBYTE
  549.     curbuf->b_p_bomb = FALSE;
  550. #endif
  551.     }
  552.  
  553.     /* Create a swap file now, so that other Vims are warned that we are
  554.      * editing this file.
  555.      * Don't do this for a "nofile" or "nowrite" buffer type. */
  556. #ifdef FEAT_QUICKFIX
  557.     if (!bt_dontwrite(curbuf))
  558. #endif
  559.     check_need_swap(newfile);
  560.  
  561. #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
  562.     /* If "Quit" selected at ATTENTION dialog, don't load the file */
  563.     if (swap_exists_action == SEA_QUIT)
  564.     {
  565.     if (!read_buffer && !read_stdin)
  566.         close(fd);
  567.     return FAIL;
  568.     }
  569. #endif
  570.  
  571.     ++no_wait_return;        /* don't wait for return yet */
  572.  
  573.     /*
  574.      * Set '[ mark to the line above where the lines go (line 1 if zero).
  575.      */
  576.     curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
  577.     curbuf->b_op_start.col = 0;
  578.  
  579. #ifdef FEAT_AUTOCMD
  580.     if (!read_buffer)
  581.     {
  582.     int    m = msg_scroll;
  583.     int    n = msg_scrolled;
  584.     buf_T    *old_curbuf = curbuf;
  585.  
  586.     /*
  587.      * The file must be closed again, the autocommands may want to change
  588.      * the file before reading it.
  589.      */
  590.     if (!read_stdin)
  591.         close(fd);        /* ignore errors */
  592.  
  593.     /*
  594.      * The output from the autocommands should not overwrite anything and
  595.      * should not be overwritten: Set msg_scroll, restore its value if no
  596.      * output was done.
  597.      */
  598.     msg_scroll = TRUE;
  599.     if (filtering)
  600.         apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
  601.                               FALSE, curbuf, eap);
  602.     else if (read_stdin)
  603.         apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
  604.                               FALSE, curbuf, eap);
  605.     else if (newfile)
  606.         apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
  607.                               FALSE, curbuf, eap);
  608.     else
  609.         apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
  610.                                 FALSE, NULL, eap);
  611.     if (msg_scrolled == n)
  612.         msg_scroll = m;
  613.  
  614.     /*
  615.      * Don't allow the autocommands to change the current buffer.
  616.      * Try to re-open the file.
  617.      */
  618.     if (!read_stdin && (curbuf != old_curbuf
  619.         || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
  620.     {
  621.         --no_wait_return;
  622.         msg_scroll = msg_save;
  623.         if (fd < 0)
  624.         EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
  625.         else
  626.         EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
  627.         return FAIL;
  628.     }
  629.     }
  630. #endif /* FEAT_AUTOCMD */
  631.  
  632.     /* Autocommands may add lines to the file, need to check if it is empty */
  633.     wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
  634.  
  635.     if (!recoverymode && !filtering && !(flags & READ_DUMMY))
  636.     {
  637.     /*
  638.      * Show the user that we are busy reading the input.  Sometimes this
  639.      * may take a while.  When reading from stdin another program may
  640.      * still be running, don't move the cursor to the last line, unless
  641.      * always using the GUI.
  642.      */
  643.     if (read_stdin)
  644.     {
  645. #ifndef ALWAYS_USE_GUI
  646.         mch_msg(_("Vim: Reading from stdin...\n"));
  647. #endif
  648. #ifdef FEAT_GUI
  649.         /* Also write a message in the GUI window, if there is one. */
  650.         if (gui.in_use)
  651.         {
  652.         p = (char_u *)_("Reading from stdin...");
  653.         gui_write(p, (int)STRLEN(p));
  654.         }
  655. #endif
  656.     }
  657.     else if (!read_buffer)
  658.         filemess(curbuf, sfname, (char_u *)"", 0);
  659.     }
  660.  
  661.     msg_scroll = FALSE;            /* overwrite the file message */
  662.  
  663.     /*
  664.      * Set linecnt now, before the "retry" caused by a wrong guess for
  665.      * fileformat, and after the autocommands, which may change them.
  666.      */
  667.     linecnt = curbuf->b_ml.ml_line_count;
  668.  
  669. #ifdef FEAT_MBYTE
  670.     /*
  671.      * Decide which 'encoding' to use first.
  672.      */
  673.     if (eap != NULL && eap->force_enc != 0)
  674.     {
  675.     fenc = enc_canonize(eap->cmd + eap->force_enc);
  676.     fenc_alloced = TRUE;
  677.     }
  678.     else if (curbuf->b_p_bin)
  679.     {
  680.     fenc = (char_u *)"";        /* binary: don't convert */
  681.     fenc_alloced = FALSE;
  682.     }
  683.     else if (*p_fencs == NUL)
  684.     {
  685.     fenc = curbuf->b_p_fenc;    /* use format from buffer */
  686.     fenc_alloced = FALSE;
  687.     }
  688.     else
  689.     {
  690.     fenc_next = p_fencs;        /* try items in 'fileencodings' */
  691.     fenc = next_fenc(&fenc_next);
  692.     fenc_alloced = TRUE;
  693.     }
  694. #endif
  695.  
  696.     /*
  697.      * Jump back here to retry reading the file in different ways.
  698.      * Reasons to retry:
  699.      * - encoding conversion failed: try another one from "fenc_next"
  700.      * - BOM detected and fenc was set, need to setup conversion
  701.      * - "fileformat" check failed: try another
  702.      *
  703.      * Variables set for special retry actions:
  704.      * "file_rewind"    Rewind the file to start reading it again.
  705.      * "advance_fenc"    Advance "fenc" using "fenc_next".
  706.      * "skip_read"    Re-use already read bytes (BOM detected).
  707.      * "did_iconv"    iconv() conversion failed, try 'charconvert'.
  708.      * "keep_fileformat" Don't reset "fileformat".
  709.      *
  710.      * Other status indicators:
  711.      * "tmpname"    When != NULL did conversion with 'charconvert'.
  712.      *            Output file has to be deleted afterwards.
  713.      * "iconv_fd"    When != -1 did conversion with iconv().
  714.      */
  715. retry:
  716.  
  717.     if (file_rewind)
  718.     {
  719.     if (read_buffer)
  720.     {
  721.         read_buf_lnum = 1;
  722.         read_buf_col = 0;
  723.     }
  724.     else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
  725.     {
  726.         /* Can't rewind the file, give up. */
  727.         error = TRUE;
  728.         goto failed;
  729.     }
  730.     /* Delete the previously read lines. */
  731.     while (lnum > from)
  732.         ml_delete(lnum--, FALSE);
  733.     file_rewind = FALSE;
  734. #ifdef FEAT_MBYTE
  735.     if (newfile)
  736.         curbuf->b_p_bomb = FALSE;
  737.     conv_error = FALSE;
  738. #endif
  739.     }
  740.  
  741.     /*
  742.      * When retrying with another "fenc" and the first time "fileformat"
  743.      * will be reset.
  744.      */
  745.     if (keep_fileformat)
  746.     keep_fileformat = FALSE;
  747.     else
  748.     {
  749.     if (eap != NULL && eap->force_ff != 0)
  750.         fileformat = get_fileformat_force(curbuf, eap);
  751.     else if (curbuf->b_p_bin)
  752.         fileformat = EOL_UNIX;        /* binary: use Unix format */
  753.     else if (*p_ffs == NUL)
  754.         fileformat = get_fileformat(curbuf);/* use format from buffer */
  755.     else
  756.         fileformat = EOL_UNKNOWN;        /* detect from file */
  757.     }
  758.  
  759. #ifdef FEAT_MBYTE
  760. # ifdef USE_ICONV
  761.     if (iconv_fd != (iconv_t)-1)
  762.     {
  763.     /* aborted conversion with iconv(), close the descriptor */
  764.     iconv_close(iconv_fd);
  765.     iconv_fd = (iconv_t)-1;
  766.     }
  767. # endif
  768.  
  769.     if (advance_fenc)
  770.     {
  771.     /*
  772.      * Try the next entry in 'fileencodings'.
  773.      */
  774.     advance_fenc = FALSE;
  775.  
  776.     if (eap != NULL && eap->force_enc != 0)
  777.     {
  778.         /* Conversion given with "++cc=" wasn't possible, read
  779.          * without conversion. */
  780.         notconverted = TRUE;
  781.         conv_error = FALSE;
  782.         if (fenc_alloced)
  783.         vim_free(fenc);
  784.         fenc = (char_u *)"";
  785.         fenc_alloced = FALSE;
  786.     }
  787.     else
  788.     {
  789.         if (fenc_alloced)
  790.         vim_free(fenc);
  791.         if (fenc_next != NULL)
  792.         {
  793.         fenc = next_fenc(&fenc_next);
  794.         fenc_alloced = (fenc_next != NULL);
  795.         }
  796.         else
  797.         {
  798.         fenc = (char_u *)"";
  799.         fenc_alloced = FALSE;
  800.         }
  801.     }
  802.     if (tmpname != NULL)
  803.     {
  804.         mch_remove(tmpname);        /* delete converted file */
  805.         vim_free(tmpname);
  806.         tmpname = NULL;
  807.     }
  808.     }
  809.  
  810.     /*
  811.      * Conversion is required when the encoding of the file is different
  812.      * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4 (requires
  813.      * conversion to UTF-8).
  814.      */
  815.     fio_flags = 0;
  816.     converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
  817.     if (converted || enc_unicode != 0)
  818.     {
  819.  
  820.     /* "ucs-bom" means we need to check the first bytes of the file
  821.      * for a BOM. */
  822.     if (STRCMP(fenc, ENC_UCSBOM) == 0)
  823.         fio_flags = FIO_UCSBOM;
  824.  
  825.     /*
  826.      * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
  827.      * done.  This is handled below after read().  Prepare the
  828.      * fio_flags to avoid having to parse the string each time.
  829.      * Also check for Unicode to Latin1 conversion, because iconv()
  830.      * appears not to handle this correctly.  This works just like
  831.      * conversion to UTF-8 except how the resulting character is put in
  832.      * the buffer.
  833.      */
  834.     else if (enc_utf8 || !has_mbyte)
  835.         fio_flags = get_fio_flags(fenc);
  836.  
  837. # ifdef USE_ICONV
  838.     /*
  839.      * Try using iconv() if we can't convert internally.
  840.      */
  841.     if (fio_flags == 0
  842. #  ifdef FEAT_EVAL
  843.         && !did_iconv
  844. #  endif
  845.         )
  846.         iconv_fd = (iconv_t)my_iconv_open(
  847.                   enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
  848. # endif
  849.  
  850. # ifdef FEAT_EVAL
  851.     /*
  852.      * Use the 'charconvert' expression when conversion is required
  853.      * and we can't do it internally or with iconv().
  854.      */
  855.     if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
  856. #  ifdef USE_ICONV
  857.                             && iconv_fd == (iconv_t)-1
  858. #  endif
  859.         )
  860.     {
  861. #  ifdef USE_ICONV
  862.         did_iconv = FALSE;
  863. #  endif
  864.         /* Skip conversion when it's already done (retry for wrong
  865.          * "fileformat"). */
  866.         if (tmpname == NULL)
  867.         {
  868.         tmpname = readfile_charconvert(fname, fenc, &fd);
  869.         if (tmpname == NULL)
  870.         {
  871.             /* Conversion failed.  Try another one. */
  872.             advance_fenc = TRUE;
  873.             if (fd < 0)
  874.             {
  875.             /* Re-opening the original file failed! */
  876.             EMSG(_("E202: Conversion made file unreadable!"));
  877.             error = TRUE;
  878.             goto failed;
  879.             }
  880.             goto retry;
  881.         }
  882.         }
  883.     }
  884.     else
  885. # endif
  886.     {
  887.         if (fio_flags == 0
  888. # ifdef USE_ICONV
  889.             && iconv_fd == (iconv_t)-1
  890. # endif
  891.            )
  892.         {
  893.         /* Conversion wanted but we can't.
  894.          * Try the next conversion in 'fileencodings' */
  895.         advance_fenc = TRUE;
  896.         goto retry;
  897.         }
  898.     }
  899.     }
  900.  
  901.     /* Set can_retry when it's possible to rewind the file and try with
  902.      * another "fenc" value.  It's FALSE when no other "fenc" to try, reading
  903.      * stdin or "fenc" was specified with "++enc=". */
  904.     can_retry = (*fenc != NUL && !read_stdin
  905.                      && (eap == NULL || eap->force_enc == 0));
  906. #endif
  907.  
  908.     if (!skip_read)
  909.     {
  910.     linerest = 0;
  911.     filesize = 0;
  912.     skip_count = lines_to_skip;
  913.     read_count = lines_to_read;
  914. #ifdef FEAT_MBYTE
  915.     conv_restlen = 0;
  916. #endif
  917.     }
  918.  
  919.     while (!error && !got_int)
  920.     {
  921.     /*
  922.      * We allocate as much space for the file as we can get, plus
  923.      * space for the old line plus room for one terminating NUL.
  924.      * The amount is limited by the fact that read() only can read
  925.      * upto max_unsigned characters (and other things).
  926.      */
  927. #if SIZEOF_INT <= 2
  928.     if (linerest >= 0x7ff0)
  929.     {
  930.         ++split;
  931.         *ptr = NL;            /* split line by inserting a NL */
  932.         size = 1;
  933.     }
  934.     else
  935. #endif
  936.     {
  937.         if (!skip_read)
  938.         {
  939. #if SIZEOF_INT > 2
  940.         size = 0x10000L;            /* use buffer >= 64K */
  941. #else
  942.         size = 0x7ff0L - linerest;        /* limit buffer to 32K */
  943. #endif
  944.  
  945.         for ( ; size >= 10; size = (long_u)size >> 1)
  946.         {
  947.             if ((new_buffer = lalloc((long_u)(size + linerest + 1),
  948.                                   FALSE)) != NULL)
  949.             break;
  950.         }
  951.         if (new_buffer == NULL)
  952.         {
  953.             do_outofmem_msg((long_u)(size * 2 + linerest + 1));
  954.             error = TRUE;
  955.             break;
  956.         }
  957.         if (linerest)    /* copy characters from the previous buffer */
  958.             mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
  959.         vim_free(buffer);
  960.         buffer = new_buffer;
  961.         ptr = buffer + linerest;
  962.         line_start = buffer;
  963.  
  964. #ifdef FEAT_MBYTE
  965.         /* May need room to translate into.
  966.          * For iconv() we don't really know the required space, use a
  967.          * factor ICONV_MULT.
  968.          * latin1 to utf-8: 1 byte becomes up to 2 bytes
  969.          * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
  970.          * become up to 4 bytes, size must be multiple of 2
  971.          * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
  972.          * multiple of 2
  973.          * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
  974.          * multiple of 4 */
  975.         real_size = size;
  976. # ifdef USE_ICONV
  977.         if (iconv_fd != (iconv_t)-1)
  978.             size = size / ICONV_MULT;
  979.         else
  980. # endif
  981.             if (fio_flags & FIO_LATIN1)
  982.             size = size / 2;
  983.         else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
  984.             size = (size * 2 / 3) & ~1;
  985.         else if (fio_flags & FIO_UCS4)
  986.             size = (size * 2 / 3) & ~3;
  987.         else if (fio_flags == FIO_UCSBOM)
  988.             size = size / ICONV_MULT;    /* worst case */
  989. #endif
  990.  
  991. #ifdef FEAT_MBYTE
  992.         if (conv_restlen > 0)
  993.         {
  994.             /* Insert unconverted bytes from previous line. */
  995.             mch_memmove(ptr, conv_rest, conv_restlen);
  996.             ptr += conv_restlen;
  997.             size -= conv_restlen;
  998.         }
  999. #endif
  1000.  
  1001.         if (read_buffer)
  1002.         {
  1003.             /*
  1004.              * Read bytes from curbuf.  Used for converting text read
  1005.              * from stdin.
  1006.              */
  1007.             if (read_buf_lnum > from)
  1008.             size = 0;
  1009.             else
  1010.             {
  1011.             int    n;
  1012.             long    tlen;
  1013.  
  1014.             tlen = 0;
  1015.             for (;;)
  1016.             {
  1017.                 p = ml_get(read_buf_lnum) + read_buf_col;
  1018.                 n = (int)STRLEN(p);
  1019.                 if ((int)tlen + n + 1 > size)
  1020.                 {
  1021.                 /* Filled up to "size", append partial line. */
  1022.                 n = size - tlen;
  1023.                 mch_memmove(ptr + tlen, p, (size_t)n);
  1024.                 read_buf_col += n;
  1025.                 break;
  1026.                 }
  1027.                 else
  1028.                 {
  1029.                 /* Append whole line and new-line. */
  1030.                 mch_memmove(ptr + tlen, p, (size_t)n);
  1031.                 tlen += n;
  1032.                 ptr[tlen++] = NL;
  1033.                 read_buf_col = 0;
  1034.                 if (++read_buf_lnum > from)
  1035.                 {
  1036.                     size = tlen;
  1037.                     break;
  1038.                 }
  1039.                 }
  1040.             }
  1041.             }
  1042.         }
  1043.         else
  1044.         {
  1045.             /*
  1046.              * Read bytes from the file.
  1047.              */
  1048.             size = vim_read(fd, ptr, size);
  1049.         }
  1050.  
  1051.         if (size <= 0)
  1052.         {
  1053.             if (size < 0)            /* read error */
  1054.             error = TRUE;
  1055. #ifdef FEAT_MBYTE
  1056.             else if (conv_restlen > 0)
  1057.             /* some trailing bytes unconverted */
  1058.             conv_error = TRUE;
  1059. #endif
  1060.         }
  1061.  
  1062. #ifdef FEAT_CRYPT
  1063.         /*
  1064.          * At start of file: Check for magic number of encryption.
  1065.          */
  1066.         if (filesize == 0)
  1067.             cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
  1068.                               &filesize, newfile);
  1069.         /*
  1070.          * Decrypt the read bytes.
  1071.          */
  1072.         if (cryptkey != NULL && size > 0)
  1073.             for (p = ptr; p < ptr + size; ++p)
  1074.             ZDECODE(*p);
  1075. #endif
  1076.         }
  1077.         skip_read = FALSE;
  1078.  
  1079. #ifdef FEAT_MBYTE
  1080.         /*
  1081.          * At start of file (or after crypt magic number): Check for BOM.
  1082.          * Also check for a BOM for other Unicode encodings, but not after
  1083.          * converting with 'charconvert' or when a BOM has already been
  1084.          * found.
  1085.          */
  1086.         if ((filesize == 0
  1087. # ifdef FEAT_CRYPT
  1088.             || (filesize == CRYPT_MAGIC_LEN && cryptkey != NULL)
  1089. # endif
  1090.                )
  1091.             && (fio_flags == FIO_UCSBOM
  1092.             || (!curbuf->b_p_bomb
  1093.                 && tmpname == NULL
  1094.                 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
  1095.         {
  1096.         char_u    *ccname;
  1097.         int    blen;
  1098.  
  1099.         /* no BOM detection in a short file or in binary mode */
  1100.         if (size < 2 || curbuf->b_p_bin)
  1101.             ccname = NULL;
  1102.         else
  1103.             ccname = check_for_bom(ptr, size, &blen,
  1104.               fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
  1105.         if (ccname != NULL)
  1106.         {
  1107.             /* Remove BOM from the text */
  1108.             filesize += blen;
  1109.             size -= blen;
  1110.             mch_memmove(ptr, ptr + blen, (size_t)size);
  1111.             if (newfile)
  1112.             curbuf->b_p_bomb = TRUE;
  1113.         }
  1114.  
  1115.         if (fio_flags == FIO_UCSBOM)
  1116.         {
  1117.             if (ccname == NULL)
  1118.             {
  1119.             /* No BOM detected: retry with next encoding. */
  1120.             advance_fenc = TRUE;
  1121.             }
  1122.             else
  1123.             {
  1124.             /* BOM detected: set "fenc" and jump back */
  1125.             if (fenc_alloced)
  1126.                 vim_free(fenc);
  1127.             fenc = ccname;
  1128.             fenc_alloced = FALSE;
  1129.             }
  1130.             /* retry reading without getting new bytes or rewinding */
  1131.             skip_read = TRUE;
  1132.             goto retry;
  1133.         }
  1134.         }
  1135. #endif
  1136.         /*
  1137.          * Break here for a read error or end-of-file.
  1138.          */
  1139.         if (size <= 0)
  1140.         break;
  1141.  
  1142. #ifdef FEAT_MBYTE
  1143.  
  1144.         /* Include not converted bytes. */
  1145.         ptr -= conv_restlen;
  1146.         size += conv_restlen;
  1147.         conv_restlen = 0;
  1148.  
  1149. # ifdef USE_ICONV
  1150.         if (iconv_fd != (iconv_t)-1)
  1151.         {
  1152.         /*
  1153.          * Attempt conversion of the read bytes to 'encoding' using
  1154.          * iconv().
  1155.          */
  1156.         const char    *fromp;
  1157.         char        *top;
  1158.         size_t        from_size;
  1159.         size_t        to_size;
  1160.  
  1161.         fromp = (char *)ptr;
  1162.         from_size = size;
  1163.         ptr += size;
  1164.         top = (char *)ptr;
  1165.         to_size = real_size - size;
  1166.  
  1167.         /*
  1168.          * If there is conversion error or not enough room try using
  1169.          * another conversion.
  1170.          */
  1171.         if ((iconv(iconv_fd, &fromp, &from_size, &top, &to_size)
  1172.                 == (size_t)-1 && ICONV_ERRNO != EINVAL)
  1173.                           || from_size > CONV_RESTLEN)
  1174.             goto rewind_retry;
  1175.  
  1176.         if (from_size > 0)
  1177.         {
  1178.             /* Some remaining characters, keep them for the next
  1179.              * round. */
  1180.             mch_memmove(conv_rest, (char_u *)fromp, from_size);
  1181.             conv_restlen = (int)from_size;
  1182.         }
  1183.  
  1184.         /* move the linerest to before the converted characters */
  1185.         line_start = ptr - linerest;
  1186.         mch_memmove(line_start, buffer, (size_t)linerest);
  1187.         size = (long)((char_u *)top - ptr);
  1188.         }
  1189. # endif
  1190.  
  1191.         if (fio_flags != 0)
  1192.         {
  1193.         int    u8c;
  1194.         char_u    *dest;
  1195.         char_u    *tail = NULL;
  1196.  
  1197.         /*
  1198.          * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
  1199.          * "enc_utf8" not set: Convert Unicode to Latin1.
  1200.          * Go from end to start through the buffer, because the number
  1201.          * of bytes may increase.
  1202.          * "dest" points to after where the UTF-8 bytes go, "p" points
  1203.          * to after the next character to convert.
  1204.          */
  1205.         dest = ptr + real_size;
  1206.         if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
  1207.         {
  1208.             p = ptr + size;
  1209.             if (fio_flags == FIO_UTF8)
  1210.             {
  1211.             /* Check for a trailing incomplete UTF-8 sequence */
  1212.             tail = ptr + size - 1;
  1213.             while (tail > ptr && (*tail & 0xc0) == 0x80)
  1214.                 --tail;
  1215.             if (tail + utf_byte2len(*tail) <= ptr + size)
  1216.                 tail = NULL;
  1217.             else
  1218.                 p = tail;
  1219.             }
  1220.         }
  1221.         else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
  1222.         {
  1223.             /* Check for a trailing byte */
  1224.             p = ptr + (size & ~1);
  1225.             if (size & 1)
  1226.             tail = p;
  1227.             if ((fio_flags & FIO_UTF16) && p > ptr)
  1228.             {
  1229.             /* Check for a trailing leading word */
  1230.             if (fio_flags & FIO_ENDIAN_L)
  1231.             {
  1232.                 u8c = (*--p << 8);
  1233.                 u8c += *--p;
  1234.             }
  1235.             else
  1236.             {
  1237.                 u8c = *--p;
  1238.                 u8c += (*--p << 8);
  1239.             }
  1240.             if (u8c >= 0xd800 && u8c <= 0xdbff)
  1241.                 tail = p;
  1242.             else
  1243.                 p += 2;
  1244.             }
  1245.         }
  1246.         else /*  FIO_UCS4 */
  1247.         {
  1248.             /* Check for trailing 1, 2 or 3 bytes */
  1249.             p = ptr + (size & ~3);
  1250.             if (size & 3)
  1251.             tail = p;
  1252.         }
  1253.  
  1254.         /* If there is a trailing incomplete sequence move it to
  1255.          * conv_rest[]. */
  1256.         if (tail != NULL)
  1257.         {
  1258.             conv_restlen = (int)((ptr + size) - tail);
  1259.             mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
  1260.             size -= conv_restlen;
  1261.         }
  1262.  
  1263.  
  1264.         while (p > ptr)
  1265.         {
  1266.             if (fio_flags & FIO_LATIN1)
  1267.             u8c = *--p;
  1268.             else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
  1269.             {
  1270.             if (fio_flags & FIO_ENDIAN_L)
  1271.             {
  1272.                 u8c = (*--p << 8);
  1273.                 u8c += *--p;
  1274.             }
  1275.             else
  1276.             {
  1277.                 u8c = *--p;
  1278.                 u8c += (*--p << 8);
  1279.             }
  1280.             if ((fio_flags & FIO_UTF16)
  1281.                         && u8c >= 0xdc00 && u8c <= 0xdfff)
  1282.             {
  1283.                 int u16c;
  1284.  
  1285.                 if (p == ptr)
  1286.                 {
  1287.                 /* Missing leading word. */
  1288.                 if (can_retry)
  1289.                     goto rewind_retry;
  1290.                 conv_error = TRUE;
  1291.                 }
  1292.  
  1293.                 /* found second word of double-word, get the first
  1294.                  * word and compute the resulting character */
  1295.                 if (fio_flags & FIO_ENDIAN_L)
  1296.                 {
  1297.                 u16c = (*--p << 8);
  1298.                 u16c += *--p;
  1299.                 }
  1300.                 else
  1301.                 {
  1302.                 u16c = *--p;
  1303.                 u16c += (*--p << 8);
  1304.                 }
  1305.                 /* Check if the word is indeed a leading word. */
  1306.                 if (u16c < 0xd800 || u16c > 0xdbff)
  1307.                 {
  1308.                 if (can_retry)
  1309.                     goto rewind_retry;
  1310.                 conv_error = TRUE;
  1311.                 }
  1312.                 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
  1313.                                   + (u8c & 0x3ff);
  1314.             }
  1315.             }
  1316.             else if (fio_flags & FIO_UCS4)
  1317.             {
  1318.             if (fio_flags & FIO_ENDIAN_L)
  1319.             {
  1320.                 u8c = (*--p << 24);
  1321.                 u8c += (*--p << 16);
  1322.                 u8c += (*--p << 8);
  1323.                 u8c += *--p;
  1324.             }
  1325.             else    /* big endian */
  1326.             {
  1327.                 u8c = *--p;
  1328.                 u8c += (*--p << 8);
  1329.                 u8c += (*--p << 16);
  1330.                 u8c += (*--p << 24);
  1331.             }
  1332.             }
  1333.             else    /* UTF-8 */
  1334.             {
  1335.             if (*--p < 0x80)
  1336.                 u8c = *p;
  1337.             else
  1338.             {
  1339.                 len = utf_head_off(ptr, p);
  1340.                 if (len == 0)
  1341.                 {
  1342.                 /* Not a valid UTF-8 character, retry with
  1343.                  * another fenc when possible, otherwise just
  1344.                  * report the error. */
  1345.                 if (can_retry)
  1346.                     goto rewind_retry;
  1347.                 conv_error = TRUE;
  1348.                 }
  1349.                 p -= len;
  1350.                 u8c = utf_ptr2char(p);
  1351.             }
  1352.             }
  1353.             if (enc_utf8)    /* produce UTF-8 */
  1354.             {
  1355.             dest -= utf_char2len(u8c);
  1356.             (void)utf_char2bytes(u8c, dest);
  1357.             }
  1358.             else        /* produce Latin1 */
  1359.             {
  1360.             --dest;
  1361.             if (u8c >= 0x100)
  1362.             {
  1363.                 /* character doesn't fit in latin1, retry with
  1364.                  * another fenc when possible, otherwise just
  1365.                  * report the error. */
  1366.                 if (can_retry)
  1367.                 goto rewind_retry;
  1368.                 *dest = 0xBF;
  1369.                 conv_error = TRUE;
  1370.             }
  1371.             else
  1372.                 *dest = u8c;
  1373.             }
  1374.         }
  1375.  
  1376.         /* move the linerest to before the converted characters */
  1377.         line_start = dest - linerest;
  1378.         mch_memmove(line_start, buffer, (size_t)linerest);
  1379.         size = (long)((ptr + real_size) - dest);
  1380.         ptr = dest;
  1381.         }
  1382.         else if (enc_utf8 && !conv_error && !curbuf->b_p_bin)
  1383.         {
  1384.         /* Converting to UTF-8: Check if the bytes are valid UTF-8.
  1385.          * Need to start before "ptr" when part of the character was
  1386.          * read in the previous read() call. */
  1387.         for (p = ptr - utf_head_off(buffer, ptr); p < ptr + size; ++p)
  1388.         {
  1389.             if (*p >= 0x80)
  1390.             {
  1391.             len = utf_ptr2len_check(p);
  1392.             /* A length of 1 means it's an illegal byte.  Accept
  1393.              * an incomplete charater at the end though, the next
  1394.              * read() will get the next bytes, we'll check it
  1395.              * then. */
  1396.             if (len == 1)
  1397.             {
  1398.                 p += utf_byte2len(*p) - 1;
  1399.                 break;
  1400.             }
  1401.             p += len - 1;
  1402.             }
  1403.         }
  1404.         if (p < ptr + size)
  1405.         {
  1406.             /* Detected a UTF-8 error. */
  1407.             if (can_retry)
  1408.             {
  1409. rewind_retry:
  1410.             /* Retry reading with another conversion. */
  1411. # if defined(FEAT_EVAL) && defined(USE_ICONV)
  1412.             if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
  1413.                 /* iconv() failed, try 'charconvert' */
  1414.                 did_iconv = TRUE;
  1415.             else
  1416. # endif
  1417.                 /* use next item from 'fileencodings' */
  1418.                 advance_fenc = TRUE;
  1419.             file_rewind = TRUE;
  1420.             goto retry;
  1421.             }
  1422.  
  1423.             /* There is no alternative fenc, just report the error. */
  1424.             conv_error = TRUE;
  1425.         }
  1426.         }
  1427. #endif
  1428.  
  1429.         /* count the number of characters (after conversion!) */
  1430.         filesize += size;
  1431.  
  1432.         /*
  1433.          * when reading the first part of a file: guess EOL type
  1434.          */
  1435.         if (fileformat == EOL_UNKNOWN)
  1436.         {
  1437.         /* First try finding a NL, for Dos and Unix */
  1438.         if (try_dos || try_unix)
  1439.         {
  1440.             for (p = ptr; p < ptr + size; ++p)
  1441.             {
  1442.             if (*p == NL)
  1443.             {
  1444.                 if (!try_unix
  1445.                     || (try_dos && p > ptr && p[-1] == CR))
  1446.                 fileformat = EOL_DOS;
  1447.                 else
  1448.                 fileformat = EOL_UNIX;
  1449.                 break;
  1450.             }
  1451.             }
  1452.  
  1453.             /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
  1454.             if (fileformat == EOL_UNIX && try_mac)
  1455.             {
  1456.             /* Need to reset the counters when retrying fenc. */
  1457.             try_mac = 1;
  1458.             try_unix = 1;
  1459.             for (; p >= ptr && *p != CR; p--)
  1460.                 ;
  1461.             if (p >= ptr)
  1462.             {
  1463.                 for (p = ptr; p < ptr + size; ++p)
  1464.                 {
  1465.                 if (*p == NL)
  1466.                     try_unix++;
  1467.                 else if (*p == CR)
  1468.                     try_mac++;
  1469.                 }
  1470.                 if (try_mac > try_unix)
  1471.                 fileformat = EOL_MAC;
  1472.             }
  1473.             }
  1474.         }
  1475.  
  1476.         /* No NL found: may use Mac format */
  1477.         if (fileformat == EOL_UNKNOWN && try_mac)
  1478.             fileformat = EOL_MAC;
  1479.  
  1480.         /* Still nothing found?  Use first format in 'ffs' */
  1481.         if (fileformat == EOL_UNKNOWN)
  1482.             fileformat = default_fileformat();
  1483.  
  1484.         /* if editing a new file: may set p_tx and p_ff */
  1485.         if (newfile)
  1486.             set_fileformat(fileformat, OPT_LOCAL);
  1487.         }
  1488.     }
  1489.  
  1490.     /*
  1491.      * This loop is executed once for every character read.
  1492.      * Keep it fast!
  1493.      */
  1494.     if (fileformat == EOL_MAC)
  1495.     {
  1496.         --ptr;
  1497.         while (++ptr, --size >= 0)
  1498.         {
  1499.         /* catch most common case first */
  1500.         if ((c = *ptr) != NUL && c != CR && c != NL)
  1501.             continue;
  1502.         if (c == NUL)
  1503.             *ptr = NL;    /* NULs are replaced by newlines! */
  1504.         else if (c == NL)
  1505.             *ptr = CR;    /* NLs are replaced by CRs! */
  1506.         else
  1507.         {
  1508.             if (skip_count == 0)
  1509.             {
  1510.             *ptr = NUL;        /* end of line */
  1511.             len = (colnr_T) (ptr - line_start + 1);
  1512.             if (ml_append(lnum, line_start, len, newfile) == FAIL)
  1513.             {
  1514.                 error = TRUE;
  1515.                 break;
  1516.             }
  1517.             ++lnum;
  1518.             if (--read_count == 0)
  1519.             {
  1520.                 error = TRUE;        /* break loop */
  1521.                 line_start = ptr;    /* nothing left to write */
  1522.                 break;
  1523.             }
  1524.             }
  1525.             else
  1526.             --skip_count;
  1527.             line_start = ptr + 1;
  1528.         }
  1529.         }
  1530.     }
  1531.     else
  1532.     {
  1533.         --ptr;
  1534.         while (++ptr, --size >= 0)
  1535.         {
  1536.         if ((c = *ptr) != NUL && c != NL)  /* catch most common case */
  1537.             continue;
  1538.         if (c == NUL)
  1539.             *ptr = NL;    /* NULs are replaced by newlines! */
  1540.         else
  1541.         {
  1542.             if (skip_count == 0)
  1543.             {
  1544.             *ptr = NUL;        /* end of line */
  1545.             len = (colnr_T)(ptr - line_start + 1);
  1546.             if (fileformat == EOL_DOS)
  1547.             {
  1548.                 if (ptr[-1] == CR)    /* remove CR */
  1549.                 {
  1550.                 ptr[-1] = NUL;
  1551.                 --len;
  1552.                 }
  1553.                 /*
  1554.                  * Reading in Dos format, but no CR-LF found!
  1555.                  * When 'fileformats' includes "unix", delete all
  1556.                  * the lines read so far and start all over again.
  1557.                  * Otherwise give an error message later.
  1558.                  */
  1559.                 else if (ff_error != EOL_DOS)
  1560.                 {
  1561.                 if (   try_unix
  1562.                     && !read_stdin
  1563.                     && (read_buffer
  1564.                     || lseek(fd, (off_t)0L, SEEK_SET) == 0))
  1565.                 {
  1566.                     fileformat = EOL_UNIX;
  1567.                     if (newfile)
  1568.                     set_fileformat(EOL_UNIX, OPT_LOCAL);
  1569.                     file_rewind = TRUE;
  1570.                     keep_fileformat = TRUE;
  1571.                     goto retry;
  1572.                 }
  1573.                 ff_error = EOL_DOS;
  1574.                 }
  1575.             }
  1576.             if (ml_append(lnum, line_start, len, newfile) == FAIL)
  1577.             {
  1578.                 error = TRUE;
  1579.                 break;
  1580.             }
  1581.             ++lnum;
  1582.             if (--read_count == 0)
  1583.             {
  1584.                 error = TRUE;        /* break loop */
  1585.                 line_start = ptr;    /* nothing left to write */
  1586.                 break;
  1587.             }
  1588.             }
  1589.             else
  1590.             --skip_count;
  1591.             line_start = ptr + 1;
  1592.         }
  1593.         }
  1594.     }
  1595.     linerest = (long)(ptr - line_start);
  1596.     ui_breakcheck();
  1597.     }
  1598.  
  1599. failed:
  1600.     /* not an error, max. number of lines reached */
  1601.     if (error && read_count == 0)
  1602.     error = FALSE;
  1603.  
  1604.     /*
  1605.      * If we get EOF in the middle of a line, note the fact and
  1606.      * complete the line ourselves.
  1607.      * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
  1608.      */
  1609.     if (!error
  1610.         && !got_int
  1611.         && linerest != 0
  1612.         && !(!curbuf->b_p_bin
  1613.         && fileformat == EOL_DOS
  1614.         && *line_start == Ctrl_Z
  1615.         && ptr == line_start + 1))
  1616.     {
  1617.     if (newfile)            /* remember for when writing */
  1618.         curbuf->b_p_eol = FALSE;
  1619.     *ptr = NUL;
  1620.     if (ml_append(lnum, line_start,
  1621.             (colnr_T)(ptr - line_start + 1), newfile) == FAIL)
  1622.         error = TRUE;
  1623.     else
  1624.         read_no_eol_lnum = ++lnum;
  1625.     }
  1626.  
  1627.     if (newfile)
  1628.     save_file_ff(curbuf);        /* remember the current file format */
  1629.  
  1630. #ifdef FEAT_CRYPT
  1631.     if (cryptkey != curbuf->b_p_key)
  1632.     vim_free(cryptkey);
  1633. #endif
  1634.  
  1635. #ifdef FEAT_MBYTE
  1636.     /* If editing a new file: set 'fenc' for the current buffer. */
  1637.     if (newfile)
  1638.     set_string_option_direct((char_u *)"fenc", -1, fenc,
  1639.                               OPT_FREE|OPT_LOCAL);
  1640.     if (fenc_alloced)
  1641.     vim_free(fenc);
  1642. # ifdef USE_ICONV
  1643.     if (iconv_fd != (iconv_t)-1)
  1644.     {
  1645.     iconv_close(iconv_fd);
  1646.     iconv_fd = (iconv_t)-1;
  1647.     }
  1648. # endif
  1649. #endif
  1650.  
  1651.     if (!read_buffer && !read_stdin)
  1652.     close(fd);                /* errors are ignored */
  1653.     vim_free(buffer);
  1654.  
  1655. #ifdef HAVE_DUP
  1656.     if (read_stdin)
  1657.     {
  1658.     /* Use stderr for stdin, makes shell commands work. */
  1659.     close(0);
  1660.     dup(2);
  1661.     }
  1662. #endif
  1663.  
  1664. #ifdef FEAT_MBYTE
  1665.     if (tmpname != NULL)
  1666.     {
  1667.     mch_remove(tmpname);        /* delete converted file */
  1668.     vim_free(tmpname);
  1669.     }
  1670. #endif
  1671.     --no_wait_return;            /* may wait for return now */
  1672.  
  1673.     /*
  1674.      * In recovery mode everything but autocommands is skipped.
  1675.      */
  1676.     if (!recoverymode)
  1677.     {
  1678.     /* need to delete the last line, which comes from the empty buffer */
  1679.     if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
  1680.     {
  1681.         ml_delete(curbuf->b_ml.ml_line_count, FALSE);
  1682.         --linecnt;
  1683.     }
  1684.     linecnt = curbuf->b_ml.ml_line_count - linecnt;
  1685.     if (filesize == 0)
  1686.         linecnt = 0;
  1687.     if (newfile || read_buffer)
  1688.         redraw_curbuf_later(NOT_VALID);
  1689.     else if (linecnt)        /* appended at least one line */
  1690.         appended_lines_mark(from, linecnt);
  1691.  
  1692. #ifdef FEAT_DIFF
  1693.     /* After reading the text into the buffer the diff info needs to be
  1694.      * updated. */
  1695.     if ((newfile || read_buffer))
  1696.         diff_invalidate();
  1697. #endif
  1698. #ifndef ALWAYS_USE_GUI
  1699.     /*
  1700.      * If we were reading from the same terminal as where messages go,
  1701.      * the screen will have been messed up.
  1702.      * Switch on raw mode now and clear the screen.
  1703.      */
  1704.     if (read_stdin)
  1705.     {
  1706.         settmode(TMODE_RAW);    /* set to raw mode */
  1707.         starttermcap();
  1708.         screenclear();
  1709.     }
  1710. #endif
  1711.  
  1712.     if (got_int)
  1713.     {
  1714.         if (!(flags & READ_DUMMY))
  1715.         filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
  1716.         msg_scroll = msg_save;
  1717. #ifdef FEAT_VIMINFO
  1718.         check_marks_read();
  1719. #endif
  1720.         return OK;        /* an interrupt isn't really an error */
  1721.     }
  1722.  
  1723.     if (!filtering && !(flags & READ_DUMMY))
  1724.     {
  1725.         msg_add_fname(curbuf, sfname);   /* fname in IObuff with quotes */
  1726.         c = FALSE;
  1727.  
  1728. #ifdef UNIX
  1729. # ifdef S_ISFIFO
  1730.         if (S_ISFIFO(perm))                /* fifo or socket */
  1731.         {
  1732.         STRCAT(IObuff, _("[fifo/socket]"));
  1733.         c = TRUE;
  1734.         }
  1735. # else
  1736. #  ifdef S_IFIFO
  1737.         if ((perm & S_IFMT) == S_IFIFO)        /* fifo */
  1738.         {
  1739.         STRCAT(IObuff, _("[fifo]"));
  1740.         c = TRUE;
  1741.         }
  1742. #  endif
  1743. #  ifdef S_IFSOCK
  1744.         if ((perm & S_IFMT) == S_IFSOCK)        /* or socket */
  1745.         {
  1746.         STRCAT(IObuff, _("[socket]"));
  1747.         c = TRUE;
  1748.         }
  1749. #  endif
  1750. # endif
  1751. #endif
  1752.         if (curbuf->b_p_ro)
  1753.         {
  1754.         STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
  1755.         c = TRUE;
  1756.         }
  1757.         if (read_no_eol_lnum)
  1758.         {
  1759.         msg_add_eol();
  1760.         c = TRUE;
  1761.         }
  1762.         if (ff_error == EOL_DOS)
  1763.         {
  1764.         STRCAT(IObuff, _("[CR missing]"));
  1765.         c = TRUE;
  1766.         }
  1767.         if (ff_error == EOL_MAC)
  1768.         {
  1769.         STRCAT(IObuff, _("[NL found]"));
  1770.         c = TRUE;
  1771.         }
  1772.         if (split)
  1773.         {
  1774.         STRCAT(IObuff, _("[long lines split]"));
  1775.         c = TRUE;
  1776.         }
  1777. #ifdef FEAT_MBYTE
  1778.         if (notconverted)
  1779.         {
  1780.         STRCAT(IObuff, _("[NOT converted]"));
  1781.         c = TRUE;
  1782.         }
  1783.         else if (converted)
  1784.         {
  1785.         STRCAT(IObuff, _("[converted]"));
  1786.         c = TRUE;
  1787.         }
  1788. #endif
  1789. #ifdef FEAT_CRYPT
  1790.         if (cryptkey != NULL)
  1791.         {
  1792.         STRCAT(IObuff, _("[crypted]"));
  1793.         c = TRUE;
  1794.         }
  1795. #endif
  1796. #ifdef FEAT_MBYTE
  1797.         if (conv_error)
  1798.         {
  1799.         STRCAT(IObuff, _("[CONVERSION ERROR]"));
  1800.         c = TRUE;
  1801.         }
  1802.         else
  1803. #endif
  1804.         if (error)
  1805.         {
  1806.         STRCAT(IObuff, _("[READ ERRORS]"));
  1807.         c = TRUE;
  1808.         }
  1809.         if (msg_add_fileformat(fileformat))
  1810.         c = TRUE;
  1811. #ifdef FEAT_CRYPT
  1812.         if (cryptkey != NULL)
  1813.         msg_add_lines(c, (long)linecnt, filesize - CRYPT_MAGIC_LEN);
  1814.         else
  1815. #endif
  1816.         msg_add_lines(c, (long)linecnt, filesize);
  1817.  
  1818.         vim_free(keep_msg);
  1819.         keep_msg = NULL;
  1820.         msg_scrolled_ign = TRUE;
  1821. #ifdef ALWAYS_USE_GUI
  1822.         /* Don't show the message when reading stdin, it would end up in a
  1823.          * message box (which might be shown when exiting!) */
  1824.         if (read_stdin || read_buffer)
  1825.         p = msg_may_trunc(FALSE, IObuff);
  1826.         else
  1827. #endif
  1828.         p = msg_trunc_attr(IObuff, FALSE, 0);
  1829.         if (read_stdin || read_buffer || restart_edit != 0
  1830.             || (msg_scrolled && !need_wait_return))
  1831.         {
  1832.         /* Need to repeat the message after redrawing when:
  1833.          * - When reading from stdin (the screen will be cleared next).
  1834.          * - When restart_edit is set (otherwise there will be a delay
  1835.          *   before redrawing).
  1836.          * - When the screen was scrolled but there is no wait-return
  1837.          *   prompt. */
  1838.         set_keep_msg(p);
  1839.         keep_msg_attr = 0;
  1840.         }
  1841.         msg_scrolled_ign = FALSE;
  1842.     }
  1843.  
  1844.     /* with errors writing the file requires ":w!" */
  1845.     if (newfile && (error
  1846. #ifdef FEAT_MBYTE
  1847.             || conv_error
  1848. #endif
  1849.             ))
  1850.         curbuf->b_p_ro = TRUE;
  1851.  
  1852.     u_clearline();        /* cannot use "U" command after adding lines */
  1853.  
  1854.     /*
  1855.      * In Ex mode: cursor at last new line.
  1856.      * Otherwise: cursor at first new line.
  1857.      */
  1858.     if (exmode_active)
  1859.         curwin->w_cursor.lnum = from + linecnt;
  1860.     else
  1861.         curwin->w_cursor.lnum = from + 1;
  1862.     check_cursor_lnum();
  1863.     beginline(BL_WHITE | BL_FIX);        /* on first non-blank */
  1864.  
  1865.     /*
  1866.      * Set '[ and '] marks to the newly read lines.
  1867.      */
  1868.     curbuf->b_op_start.lnum = from + 1;
  1869.     curbuf->b_op_start.col = 0;
  1870.     curbuf->b_op_end.lnum = from + linecnt;
  1871.     curbuf->b_op_end.col = 0;
  1872.     }
  1873.     msg_scroll = msg_save;
  1874.  
  1875. #ifdef FEAT_VIMINFO
  1876.     /*
  1877.      * Get the marks before executing autocommands, so they can be used there.
  1878.      */
  1879.     check_marks_read();
  1880. #endif
  1881.  
  1882. #ifdef FEAT_AUTOCMD
  1883.     /*
  1884.      * Trick: We remember if the last line of the read didn't have
  1885.      * an eol for when writing it again.  This is required for
  1886.      * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
  1887.      */
  1888.     write_no_eol_lnum = read_no_eol_lnum;
  1889.  
  1890.     if (!read_stdin && !read_buffer)
  1891.     {
  1892.     int m = msg_scroll;
  1893.     int n = msg_scrolled;
  1894.  
  1895.     /*
  1896.      * The output from the autocommands should not overwrite anything and
  1897.      * should not be overwritten: Set msg_scroll, restore its value if no
  1898.      * output was done.
  1899.      */
  1900.     msg_scroll = TRUE;
  1901.     if (filtering)
  1902.         apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
  1903.                               FALSE, curbuf, eap);
  1904.     else if (newfile)
  1905.         apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
  1906.                               FALSE, curbuf, eap);
  1907.     else
  1908.         apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
  1909.                                 FALSE, NULL, eap);
  1910.     if (msg_scrolled == n)
  1911.         msg_scroll = m;
  1912.     }
  1913. #endif
  1914.  
  1915.     if (recoverymode && error)
  1916.     return FAIL;
  1917.     return OK;
  1918. }
  1919.  
  1920. /*
  1921.  * Fill "*eap" to force the 'fileencoding' and 'fileformat' to be equal to the
  1922.  * buffer "buf".  Used for calling readfile().
  1923.  * Returns OK or FAIL.
  1924.  */
  1925.     int
  1926. prep_exarg(eap, buf)
  1927.     exarg_T    *eap;
  1928.     buf_T    *buf;
  1929. {
  1930.     eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
  1931. #ifdef FEAT_MBYTE
  1932.         + STRLEN(buf->b_p_fenc)
  1933. #endif
  1934.                          + 15));
  1935.     if (eap->cmd == NULL)
  1936.     return FAIL;
  1937.  
  1938. #ifdef FEAT_MBYTE
  1939.     sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
  1940.     eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
  1941. #else
  1942.     sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
  1943. #endif
  1944.     eap->force_ff = 7;
  1945.     return OK;
  1946. }
  1947.  
  1948. #ifdef FEAT_MBYTE
  1949. /*
  1950.  * Find next fileencoding to use from 'fileencodings'.
  1951.  * "pp" points to fenc_next.  It's advanced to the next item.
  1952.  * When there are no more items, an empty string is returned and *pp is set to
  1953.  * NULL.
  1954.  * When *pp is not set to NULL, the result is in allocated memory.
  1955.  */
  1956.     static char_u *
  1957. next_fenc(pp)
  1958.     char_u    **pp;
  1959. {
  1960.     char_u    *p;
  1961.     char_u    *r;
  1962.  
  1963.     if (**pp == NUL)
  1964.     {
  1965.     *pp = NULL;
  1966.     return (char_u *)"";
  1967.     }
  1968.     p = vim_strchr(*pp, ',');
  1969.     if (p == NULL)
  1970.     {
  1971.     r = enc_canonize(*pp);
  1972.     *pp += STRLEN(*pp);
  1973.     }
  1974.     else
  1975.     {
  1976.     r = vim_strnsave(*pp, (int)(p - *pp));
  1977.     *pp = p + 1;
  1978.     if (r != NULL)
  1979.     {
  1980.         p = enc_canonize(r);
  1981.         vim_free(r);
  1982.         r = p;
  1983.     }
  1984.     }
  1985.     if (r == NULL)    /* out of memory */
  1986.     {
  1987.     r = (char_u *)"";
  1988.     *pp = NULL;
  1989.     }
  1990.     return r;
  1991. }
  1992.  
  1993. # ifdef FEAT_EVAL
  1994. /*
  1995.  * Convert a file with the 'charconvert' expression.
  1996.  * This closes the file which is to be read, converts it and opens the
  1997.  * resulting file for reading.
  1998.  * Returns name of the resulting converted file (the caller should delete it
  1999.  * after reading it).
  2000.  * Returns NULL if the conversion failed ("*fdp" is not set) .
  2001.  */
  2002.     static char_u *
  2003. readfile_charconvert(fname, fenc, fdp)
  2004.     char_u    *fname;        /* name of input file */
  2005.     char_u    *fenc;        /* converted from */
  2006.     int        *fdp;        /* in/out: file descriptor of file */
  2007. {
  2008.     char_u    *tmpname;
  2009.     char_u    *errmsg = NULL;
  2010.  
  2011.     tmpname = vim_tempname('r');
  2012.     if (tmpname == NULL)
  2013.     errmsg = (char_u *)_("Can't find temp file for conversion");
  2014.     else
  2015.     {
  2016.     close(*fdp);        /* close the input file, ignore errors */
  2017.     *fdp = -1;
  2018.     if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
  2019.                               fname, tmpname) == FAIL)
  2020.         errmsg = (char_u *)_("Conversion with 'charconvert' failed");
  2021.     if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
  2022.                           O_RDONLY | O_EXTRA, 0)) < 0)
  2023.         errmsg = (char_u *)_("can't read output of 'charconvert'");
  2024.     }
  2025.  
  2026.     if (errmsg != NULL)
  2027.     {
  2028.     /* Don't use emsg(), it breaks mappings, the retry with
  2029.      * another type of conversion might still work. */
  2030.     MSG(errmsg);
  2031.     if (tmpname != NULL)
  2032.     {
  2033.         mch_remove(tmpname);    /* delete converted file */
  2034.         vim_free(tmpname);
  2035.         tmpname = NULL;
  2036.     }
  2037.     }
  2038.  
  2039.     /* If the input file is closed, open it (caller should check for error). */
  2040.     if (*fdp < 0)
  2041.     *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
  2042.  
  2043.     return tmpname;
  2044. }
  2045. # endif
  2046.  
  2047. #endif
  2048.  
  2049. #ifdef FEAT_VIMINFO
  2050.     static void
  2051. check_marks_read()
  2052. {
  2053.     if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0)
  2054.     {
  2055.     read_viminfo(NULL, FALSE, TRUE, FALSE);
  2056.     curbuf->b_marks_read = TRUE;
  2057.     }
  2058. }
  2059. #endif
  2060.  
  2061. #ifdef FEAT_CRYPT
  2062. /*
  2063.  * Check for magic number used for encryption.
  2064.  * If found, the magic number is removed from ptr[*sizep] and *sizep and
  2065.  * *filesizep are updated.
  2066.  * Return the (new) encryption key, NULL for no encryption.
  2067.  */
  2068.     static char_u *
  2069. check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile)
  2070.     char_u    *cryptkey;    /* previous encryption key or NULL */
  2071.     char_u    *ptr;        /* pointer to read bytes */
  2072.     long    *sizep;        /* length of read bytes */
  2073.     long    *filesizep;    /* nr of bytes used from file */
  2074.     int        newfile;    /* editing a new buffer */
  2075. {
  2076.     if (*sizep >= CRYPT_MAGIC_LEN
  2077.         && STRNCMP(ptr, CRYPT_MAGIC, CRYPT_MAGIC_LEN) == 0)
  2078.     {
  2079.     if (cryptkey == NULL)
  2080.     {
  2081.         if (*curbuf->b_p_key)
  2082.         cryptkey = curbuf->b_p_key;
  2083.         else
  2084.         {
  2085.         /* When newfile is TRUE, store the typed key
  2086.          * in the 'key' option and don't free it. */
  2087.         cryptkey = get_crypt_key(newfile, FALSE);
  2088.         /* check if empty key entered */
  2089.         if (cryptkey != NULL && *cryptkey == NUL)
  2090.         {
  2091.             if (cryptkey != curbuf->b_p_key)
  2092.             vim_free(cryptkey);
  2093.             cryptkey = NULL;
  2094.         }
  2095.         }
  2096.     }
  2097.  
  2098.     if (cryptkey != NULL)
  2099.     {
  2100.         crypt_init_keys(cryptkey);
  2101.  
  2102.         /* Remove magic number from the text */
  2103.         *filesizep += CRYPT_MAGIC_LEN;
  2104.         *sizep -= CRYPT_MAGIC_LEN;
  2105.         mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN, (size_t)*sizep);
  2106.     }
  2107.     }
  2108.     /* When starting to edit a new file which does not have
  2109.      * encryption, clear the 'key' option, except when
  2110.      * starting up (called with -x argument) */
  2111.     else if (newfile && *curbuf->b_p_key && !starting)
  2112.     set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
  2113.  
  2114.     return cryptkey;
  2115. }
  2116. #endif
  2117.  
  2118. #ifdef UNIX
  2119.     static void
  2120. set_file_time(fname, atime, mtime)
  2121.     char_u  *fname;
  2122.     time_t  atime;        /* access time */
  2123.     time_t  mtime;        /* modification time */
  2124. {
  2125. # if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
  2126. #  include <utime.h>
  2127.  
  2128.     struct utimbuf  buf;
  2129.  
  2130.     buf.actime    = atime;
  2131.     buf.modtime    = mtime;
  2132.     (void)utime((char *)fname, &buf);
  2133. # else
  2134. #  if defined(HAVE_UTIMES)
  2135.  
  2136.     struct timeval  tvp[2];
  2137.  
  2138.     tvp[0].tv_sec   = atime;
  2139.     tvp[0].tv_usec  = 0;
  2140.     tvp[1].tv_sec   = mtime;
  2141.     tvp[1].tv_usec  = 0;
  2142. #   ifdef NeXT
  2143.     (void)utimes((char *)fname, tvp);
  2144. #   else
  2145.     (void)utimes((char *)fname, &tvp);
  2146. #   endif
  2147. #  endif
  2148. # endif
  2149. }
  2150. #endif /* UNIX */
  2151.  
  2152. /*
  2153.  * buf_write() - write to file 'fname' lines 'start' through 'end'
  2154.  *
  2155.  * We do our own buffering here because fwrite() is so slow.
  2156.  *
  2157.  * If forceit is true, we don't care for errors when attempting backups (jw).
  2158.  * In case of an error everything possible is done to restore the original file.
  2159.  * But when forceit is TRUE, we risk loosing it.
  2160.  * When reset_changed is TRUE and start == 1 and end ==
  2161.  * curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
  2162.  *
  2163.  * This function must NOT use NameBuff (because it's called by autowrite()).
  2164.  *
  2165.  * return FAIL for failure, OK otherwise
  2166.  */
  2167.     int
  2168. buf_write(buf, fname, sfname, start, end, eap, append, forceit,
  2169.                               reset_changed, filtering)
  2170.     buf_T        *buf;
  2171.     char_u        *fname;
  2172.     char_u        *sfname;
  2173.     linenr_T        start, end;
  2174.     exarg_T        *eap;        /* for forced 'ff' and 'fenc', can be
  2175.                        NULL! */
  2176.     int            append;
  2177.     int            forceit;
  2178.     int            reset_changed;
  2179.     int            filtering;
  2180. {
  2181.     int            fd;
  2182.     char_u        *backup = NULL;
  2183.     int            backup_copy = FALSE; /* copy the original file? */
  2184.     int            dobackup;
  2185.     char_u        *ffname;
  2186.     char_u        *wfname;        /* name of file to write to */
  2187.     char_u        *s;
  2188.     char_u        *ptr;
  2189.     char_u        c;
  2190.     int            len;
  2191.     linenr_T        lnum;
  2192.     long        nchars;
  2193.     char_u        *errmsg = NULL;
  2194.     char_u        *buffer;
  2195.     char_u        smallbuf[SMBUFSIZE];
  2196.     char_u        *backup_ext;
  2197.     int            bufsize;
  2198.     long        perm;            /* file permissions */
  2199.     int            retval = OK;
  2200.     int            newfile = FALSE;        /* TRUE if file doesn't exist yet */
  2201.     int            msg_save = msg_scroll;
  2202.     int            overwriting;        /* TRUE if writing over original */
  2203.     int            no_eol = FALSE;        /* no end-of-line written */
  2204.     int            device = FALSE;        /* writing to a device */
  2205.     struct stat        st_old;
  2206.     int            prev_got_int = got_int;
  2207. #if defined(UNIX) || defined(__EMX__XX)        /*XXX fix me sometime? */
  2208.     int            made_writable = FALSE;  /* 'w' bit has been set */
  2209. #endif
  2210. #ifdef VMS
  2211.     char_u        nfname[MAXPATHL];
  2212. #endif
  2213.                     /* writing everything */
  2214.     int            whole = (start == 1 && end == buf->b_ml.ml_line_count);
  2215. #ifdef FEAT_AUTOCMD
  2216.     linenr_T        old_line_count = buf->b_ml.ml_line_count;
  2217. #endif
  2218.     int            attr;
  2219.     int            fileformat;
  2220.     struct bw_info  write_info;        /* info for buf_write_bytes() */
  2221. #ifdef FEAT_MBYTE
  2222.     int            converted = FALSE;
  2223.     int            notconverted = FALSE;
  2224.     char_u        *fenc;        /* effective 'fileencoding' */
  2225.     char_u        *fenc_tofree = NULL; /* allocated "fenc" */
  2226. #endif
  2227. #ifdef HAS_BW_FLAGS
  2228.     int            wb_flags = 0;
  2229. #endif
  2230. #ifdef HAVE_ACL
  2231.     vim_acl_T        acl = NULL;        /* ACL copied from original file to
  2232.                        backup or new file */
  2233. #endif
  2234.  
  2235.     if (fname == NULL || *fname == NUL)    /* safety check */
  2236.     return FAIL;
  2237.  
  2238.     /*
  2239.      * Disallow writing from .exrc and .vimrc in current directory for
  2240.      * security reasons.
  2241.      */
  2242.     if (check_secure())
  2243.     return FAIL;
  2244.  
  2245.     /* Avoid a crash for a long name. */
  2246.     if (STRLEN(fname) >= MAXPATHL)
  2247.     {
  2248.     EMSG(_(e_longname));
  2249.     return FAIL;
  2250.     }
  2251.  
  2252. #ifdef FEAT_MBYTE
  2253.     /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
  2254.     write_info.bw_conv_buf = NULL;
  2255.     write_info.bw_conv_error = FALSE;
  2256.     write_info.bw_restlen = 0;
  2257. # ifdef USE_ICONV
  2258.     write_info.bw_iconv_fd = (iconv_t)-1;
  2259. # endif
  2260. #endif
  2261.  
  2262.     /*
  2263.      * If there is no file name yet, use the one for the written file.
  2264.      * BF_NOTEDITED is set to reflect this (in case the write fails).
  2265.      * Don't do this when the write is for a filter command.
  2266.      * Only do this when 'cpoptions' contains the 'f' flag.
  2267.      */
  2268.     if (reset_changed
  2269.         && whole
  2270.         && buf == curbuf
  2271.         && curbuf->b_ffname == NULL
  2272.         && !filtering
  2273.         && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
  2274.     {
  2275. #ifdef FEAT_AUTOCMD
  2276.     /* It's like the unnamed buffer is deleted.... */
  2277.     if (curbuf->b_p_bl)
  2278.         apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
  2279.     apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
  2280. #endif
  2281.     if (setfname(fname, sfname, FALSE) == OK)
  2282.         curbuf->b_flags |= BF_NOTEDITED;
  2283. #ifdef FEAT_AUTOCMD
  2284.     /* ....and a new named one is created */
  2285.     apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
  2286.     if (curbuf->b_p_bl)
  2287.         apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
  2288. #endif
  2289.     }
  2290.  
  2291.     if (sfname == NULL)
  2292.     sfname = fname;
  2293.     /*
  2294.      * For Unix: Use the short file name whenever possible.
  2295.      * Avoids problems with networks and when directory names are changed.
  2296.      * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
  2297.      * another directory, which we don't detect
  2298.      */
  2299.     ffname = fname;                /* remember full fname */
  2300. #ifdef UNIX
  2301.     fname = sfname;
  2302. #endif
  2303.  
  2304.     /* make sure we have a valid backup extension to use */
  2305.     if (*p_bex == NUL)
  2306. #ifdef RISCOS
  2307.     backup_ext = (char_u *)"/bak";
  2308. #else
  2309.     backup_ext = (char_u *)".bak";
  2310. #endif
  2311.     else
  2312.     backup_ext = p_bex;
  2313.  
  2314.     if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
  2315.     overwriting = TRUE;
  2316.     else
  2317.     overwriting = FALSE;
  2318.  
  2319.     if (exiting)
  2320.     settmode(TMODE_COOK);        /* when exiting allow typahead now */
  2321.  
  2322.     ++no_wait_return;            /* don't wait for return yet */
  2323.  
  2324.     /*
  2325.      * Set '[ and '] marks to the lines to be written.
  2326.      */
  2327.     buf->b_op_start.lnum = start;
  2328.     buf->b_op_start.col = 0;
  2329.     buf->b_op_end.lnum = end;
  2330.     buf->b_op_end.col = 0;
  2331.  
  2332. #ifdef FEAT_AUTOCMD
  2333.     {
  2334.     aco_save_T    aco;
  2335.     int        buf_ffname = FALSE;
  2336.     int        buf_sfname = FALSE;
  2337.     int        buf_fname_f = FALSE;
  2338.     int        buf_fname_s = FALSE;
  2339.     int        did_cmd = FALSE;
  2340.  
  2341.     /*
  2342.      * Apply PRE aucocommands.
  2343.      * Set curbuf to the buffer to be written.
  2344.      * Careful: The autocommands may call buf_write() recursively!
  2345.      */
  2346.     if (ffname == buf->b_ffname)
  2347.         buf_ffname = TRUE;
  2348.     if (sfname == buf->b_sfname)
  2349.         buf_sfname = TRUE;
  2350.     if (fname == buf->b_ffname)
  2351.         buf_fname_f = TRUE;
  2352.     if (fname == buf->b_sfname)
  2353.         buf_fname_s = TRUE;
  2354.  
  2355.     /* set curwin/curbuf to buf and save a few things */
  2356.     aucmd_prepbuf(&aco, buf);
  2357.  
  2358.     if (append)
  2359.     {
  2360.         if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
  2361.                        fname, fname, FALSE, curbuf, eap)))
  2362.         apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
  2363.                         fname, fname, FALSE, curbuf, eap);
  2364.     }
  2365.     else if (filtering)
  2366.     {
  2367.         apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
  2368.                          NULL, fname, FALSE, curbuf, eap);
  2369.     }
  2370.     else if (reset_changed && whole)
  2371.     {
  2372.         if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
  2373.                        fname, fname, FALSE, curbuf, eap)))
  2374.         apply_autocmds_exarg(EVENT_BUFWRITEPRE,
  2375.                         fname, fname, FALSE, curbuf, eap);
  2376.     }
  2377.     else
  2378.     {
  2379.         if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
  2380.                        fname, fname, FALSE, curbuf, eap)))
  2381.         apply_autocmds_exarg(EVENT_FILEWRITEPRE,
  2382.                         fname, fname, FALSE, curbuf, eap);
  2383.     }
  2384.  
  2385.     /* restore curwin/curbuf and a few other things */
  2386.     aucmd_restbuf(&aco);
  2387.  
  2388.     /*
  2389.      * In two situations we return here and don't write the file:
  2390.      * 1. the autocommands deleted or unloaded the buffer.
  2391.      * 2. If one of the "Cmd" autocommands was executed.
  2392.      */
  2393.     if (!buf_valid(buf) || buf->b_ml.ml_mfp == NULL || did_cmd)
  2394.     {
  2395.         --no_wait_return;
  2396.         msg_scroll = msg_save;
  2397.         if (did_cmd)
  2398.         {
  2399.         if (!exiting && overwriting)
  2400.         {
  2401.             /* Assume the buffer was written, update the timestamp. */
  2402.             ml_timestamp(buf);
  2403.             buf->b_flags &= ~BF_WRITE_MASK;
  2404.         }
  2405.         return OK;
  2406.         }
  2407.         EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
  2408.         return FAIL;
  2409.     }
  2410.  
  2411.     /*
  2412.      * The autocommands may have changed the number of lines in the file.
  2413.      * When writing the whole file, adjust the end.
  2414.      * When writing part of the file, assume that the autocommands only
  2415.      * changed the number of lines that are to be written (tricky!).
  2416.      */
  2417.     if (buf->b_ml.ml_line_count != old_line_count)
  2418.     {
  2419.         if (whole)                        /* write all */
  2420.         end = buf->b_ml.ml_line_count;
  2421.         else if (buf->b_ml.ml_line_count > old_line_count)    /* more lines */
  2422.         end += buf->b_ml.ml_line_count - old_line_count;
  2423.         else                        /* less lines */
  2424.         {
  2425.         end -= old_line_count - buf->b_ml.ml_line_count;
  2426.         if (end < start)
  2427.         {
  2428.             --no_wait_return;
  2429.             msg_scroll = msg_save;
  2430.             EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
  2431.             return FAIL;
  2432.         }
  2433.         }
  2434.     }
  2435.  
  2436.     /*
  2437.      * The autocommands may have changed the name of the buffer, which may
  2438.      * be kept in fname, ffname and sfname.
  2439.      */
  2440.     if (buf_ffname)
  2441.         ffname = buf->b_ffname;
  2442.     if (buf_sfname)
  2443.         sfname = buf->b_sfname;
  2444.     if (buf_fname_f)
  2445.         fname = buf->b_ffname;
  2446.     if (buf_fname_s)
  2447.         fname = buf->b_sfname;
  2448.     }
  2449. #endif
  2450.  
  2451.     if (shortmess(SHM_OVER) && !exiting)
  2452.     msg_scroll = FALSE;        /* overwrite previous file message */
  2453.     else
  2454.     msg_scroll = TRUE;        /* don't overwrite previous file message */
  2455.     if (!filtering)
  2456.     filemess(buf,
  2457. #ifndef UNIX
  2458.         sfname,
  2459. #else
  2460.         fname,
  2461. #endif
  2462.             (char_u *)"", 0);    /* show that we are busy */
  2463.     msg_scroll = FALSE;            /* always overwrite the file message now */
  2464.  
  2465.     buffer = alloc(BUFSIZE);
  2466.     if (buffer == NULL)            /* can't allocate big buffer, use small
  2467.                      * one (to be able to write when out of
  2468.                      * memory) */
  2469.     {
  2470.     buffer = smallbuf;
  2471.     bufsize = SMBUFSIZE;
  2472.     }
  2473.     else
  2474.     bufsize = BUFSIZE;
  2475.  
  2476.     /*
  2477.      * Get information about original file (if there is one).
  2478.      */
  2479. #if defined(UNIX) && !defined(ARCHIE)
  2480.     st_old.st_dev = st_old.st_ino = 0;
  2481.     perm = -1;
  2482.     if (mch_stat((char *)fname, &st_old) < 0)
  2483.     newfile = TRUE;
  2484.     else
  2485.     {
  2486.     perm = st_old.st_mode;
  2487.     if (!S_ISREG(st_old.st_mode))        /* not a file */
  2488.     {
  2489.         if (S_ISDIR(st_old.st_mode))
  2490.         {
  2491.         errmsg = (char_u *)_("is a directory");
  2492.         goto fail;
  2493.         }
  2494.         if (mch_nodetype(fname) != NODE_WRITABLE)
  2495.         {
  2496.         errmsg = (char_u *)_("is not a file or writable device");
  2497.         goto fail;
  2498.         }
  2499.         /* It's a device of some kind (or a fifo) which we can write to
  2500.          * but for which we can't make a backup. */
  2501.         device = TRUE;
  2502.         newfile = TRUE;
  2503.         perm = -1;
  2504.     }
  2505.     }
  2506. #else /* !UNIX */
  2507.     /*
  2508.      * Check for a writable device name.
  2509.      */
  2510.     c = mch_nodetype(fname);
  2511.     if (c == NODE_OTHER)
  2512.     {
  2513.     errmsg = (char_u *)_("is not a file or writable device");
  2514.     goto fail;
  2515.     }
  2516.     if (c == NODE_WRITABLE)
  2517.     {
  2518.     device = TRUE;
  2519.     newfile = TRUE;
  2520.     perm = -1;
  2521.     }
  2522.     else
  2523.     {
  2524.     perm = mch_getperm(fname);
  2525.     if (perm < 0)
  2526.         newfile = TRUE;
  2527.     else if (mch_isdir(fname))
  2528.     {
  2529.         errmsg = (char_u *)_("is a directory");
  2530.         goto fail;
  2531.     }
  2532.     if (overwriting)
  2533.         (void)mch_stat((char *)fname, &st_old);
  2534.     }
  2535. #endif /* !UNIX */
  2536.  
  2537.     if (!device && !newfile)
  2538.     {
  2539.     /*
  2540.      * Check if the file is really writable (when renaming the file to
  2541.      * make a backup we won't discover it later).
  2542.      */
  2543.     if (!forceit && (
  2544. # ifdef USE_MCH_ACCESS
  2545. #  ifdef UNIX
  2546.             (perm & 0222) == 0 ||
  2547. #  endif
  2548.             mch_access((char *)fname, W_OK)
  2549. # else
  2550.             (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
  2551.             ? TRUE : (close(fd), FALSE)
  2552. # endif
  2553.             ))
  2554.     {
  2555.         errmsg = (char_u *)_("is read-only (use ! to override)");
  2556.         goto fail;
  2557.     }
  2558.  
  2559.     /*
  2560.      * Check if the timestamp hasn't changed since reading the file.
  2561.      */
  2562.     if (overwriting)
  2563.     {
  2564.         retval = check_mtime(buf, &st_old);
  2565.         if (retval == FAIL)
  2566.         goto fail;
  2567.     }
  2568.     }
  2569.  
  2570. #ifdef HAVE_ACL
  2571.     /*
  2572.      * For systems that support ACL: get the ACL from the original file.
  2573.      */
  2574.     if (!newfile)
  2575.     acl = mch_get_acl(fname);
  2576. #endif
  2577.  
  2578.     /*
  2579.      * If 'backupskip' is not empty, don't make a backup for some files.
  2580.      */
  2581.     dobackup = (p_wb || p_bk || *p_pm != NUL);
  2582. #ifdef FEAT_WILDIGN
  2583.     if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
  2584.     dobackup = FALSE;
  2585. #endif
  2586.  
  2587.     /*
  2588.      * Save the value of got_int and reset it.  We don't want a previous
  2589.      * interruption cancel writing, only hitting CTRL-C while writing should
  2590.      * abort it.
  2591.      */
  2592.     prev_got_int = got_int;
  2593.     got_int = FALSE;
  2594.  
  2595.     /*
  2596.      * If we are not appending or filtering, the file exists, and the
  2597.      * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
  2598.      * When 'patchmode' is set also make a backup when appending.
  2599.      *
  2600.      * Do not make any backup, if 'writebackup' and 'backup' are both switched
  2601.      * off.  This helps when editing large files on almost-full disks.
  2602.      */
  2603.     if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
  2604.     {
  2605.     if (*p_bkc == 'y' || append)    /* "yes" */
  2606.         backup_copy = TRUE;
  2607. #ifdef UNIX
  2608.     else if (*p_bkc == 'a')        /* "auto" */
  2609.     {
  2610.         struct stat    st;
  2611.         int        i;
  2612.  
  2613.         /*
  2614.          * Don't rename the file when:
  2615.          * - it's a hard link
  2616.          * - it's a symbolic link
  2617.          * - we don't have write permission in the directory
  2618.          * - we can't set the owner/group of the new file
  2619.          */
  2620.         if (st_old.st_nlink > 1
  2621.             || mch_lstat((char *)fname, &st) < 0
  2622.             || st.st_dev != st_old.st_dev
  2623.             || st.st_ino != st_old.st_ino)
  2624.         backup_copy = TRUE;
  2625.         else
  2626.         {
  2627.         /*
  2628.          * Check if we can create a file and set the owner/group to
  2629.          * the ones from the original file.
  2630.          * First find a file name that doesn't exist yet (use some
  2631.          * arbitrary numbers).
  2632.          */
  2633.         STRCPY(IObuff, fname);
  2634.         for (i = 4913; ; i += 123)
  2635.         {
  2636.             sprintf((char *)gettail(IObuff), "%d", i);
  2637.             if (mch_stat((char *)IObuff, &st) < 0)
  2638.             break;
  2639.         }
  2640.         fd = mch_open((char *)IObuff, O_CREAT|O_WRONLY|O_EXCL, perm);
  2641.         close(fd);
  2642.         if (fd < 0)    /* can't write in directory */
  2643.             backup_copy = TRUE;
  2644.         else
  2645.         {
  2646.             chown((char *)IObuff, st_old.st_uid, st_old.st_gid);
  2647.             if (mch_stat((char *)IObuff, &st) < 0
  2648.                 || st.st_uid != st_old.st_uid
  2649.                 || st.st_gid != st_old.st_gid)
  2650.             backup_copy = TRUE;
  2651.             mch_remove(IObuff);
  2652.         }
  2653.         }
  2654.     }
  2655. #endif
  2656.  
  2657.     if (backup_copy
  2658.         && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
  2659.     {
  2660.         int        bfd;
  2661.         char_u    *copybuf, *wp;
  2662.         int        some_error = FALSE;
  2663.         struct stat    st_new;
  2664.         char_u    *dirp;
  2665.         char_u    *rootname;
  2666. #ifndef SHORT_FNAME
  2667.         int        did_set_shortname;
  2668. #endif
  2669.  
  2670.         copybuf = alloc(BUFSIZE + 1);
  2671.         if (copybuf == NULL)
  2672.         {
  2673.         some_error = TRUE;        /* out of memory */
  2674.         goto nobackup;
  2675.         }
  2676.  
  2677.         /*
  2678.          * Try to make the backup in each directory in the 'bdir' option.
  2679.          *
  2680.          * Unix semantics has it, that we may have a writable file,
  2681.          * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
  2682.          *  - the directory is not writable,
  2683.          *  - the file may be a symbolic link,
  2684.          *  - the file may belong to another user/group, etc.
  2685.          *
  2686.          * For these reasons, the existing writable file must be truncated
  2687.          * and reused. Creation of a backup COPY will be attempted.
  2688.          */
  2689.         dirp = p_bdir;
  2690.         while (*dirp)
  2691.         {
  2692. #ifdef UNIX
  2693.         st_new.st_ino = 0;
  2694.         st_new.st_dev = 0;
  2695.         st_new.st_gid = 0;
  2696. #endif
  2697.  
  2698.         /*
  2699.          * Isolate one directory name, using an entry in 'bdir'.
  2700.          */
  2701.         (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
  2702.         rootname = get_file_in_dir(fname, copybuf);
  2703.         if (rootname == NULL)
  2704.         {
  2705.             some_error = TRUE;        /* out of memory */
  2706.             goto nobackup;
  2707.         }
  2708.  
  2709. #ifndef SHORT_FNAME
  2710.         did_set_shortname = FALSE;
  2711. #endif
  2712.  
  2713.         /*
  2714.          * May try twice if 'shortname' not set.
  2715.          */
  2716.         for (;;)
  2717.         {
  2718.             /*
  2719.              * Make backup file name.
  2720.              */
  2721.             backup = buf_modname(
  2722. #ifdef SHORT_FNAME
  2723.                 TRUE,
  2724. #else
  2725.                 (buf->b_p_sn || buf->b_shortname),
  2726. #endif
  2727.                          rootname, backup_ext, FALSE);
  2728.             if (backup == NULL)
  2729.             {
  2730.             vim_free(rootname);
  2731.             some_error = TRUE;        /* out of memory */
  2732.             goto nobackup;
  2733.             }
  2734.  
  2735.             /*
  2736.              * Check if backup file already exists.
  2737.              */
  2738.             if (mch_stat((char *)backup, &st_new) >= 0)
  2739.             {
  2740. #ifdef UNIX
  2741.             /*
  2742.              * Check if backup file is same as original file.
  2743.              * May happen when modname() gave the same file back.
  2744.              * E.g. silly link, or file name-length reached.
  2745.              * If we don't check here, we either ruin the file
  2746.              * when copying or erase it after writing. jw.
  2747.              */
  2748.             if (st_new.st_dev == st_old.st_dev
  2749.                         && st_new.st_ino == st_old.st_ino)
  2750.             {
  2751.                 vim_free(backup);
  2752.                 backup = NULL;    /* no backup file to delete */
  2753. # ifndef SHORT_FNAME
  2754.                 /*
  2755.                  * may try again with 'shortname' set
  2756.                  */
  2757.                 if (!(buf->b_shortname || buf->b_p_sn))
  2758.                 {
  2759.                 buf->b_shortname = TRUE;
  2760.                 did_set_shortname = TRUE;
  2761.                 continue;
  2762.                 }
  2763.                 /* setting shortname didn't help */
  2764.                 if (did_set_shortname)
  2765.                 buf->b_shortname = FALSE;
  2766. # endif
  2767.                 break;
  2768.             }
  2769. #endif
  2770.  
  2771.             /*
  2772.              * If we are not going to keep the backup file, don't
  2773.              * delete an existing one, try to use another name.
  2774.              * Change one character, just before the extension.
  2775.              */
  2776.             if (!p_bk)
  2777.             {
  2778.                 wp = backup + STRLEN(backup) - 1
  2779.                              - STRLEN(backup_ext);
  2780.                 if (wp < backup)    /* empty file name ??? */
  2781.                 wp = backup;
  2782.                 *wp = 'z';
  2783.                 while (*wp > 'a'
  2784.                     && mch_stat((char *)backup, &st_new) >= 0)
  2785.                 --*wp;
  2786.                 /* They all exist??? Must be something wrong. */
  2787.                 if (*wp == 'a')
  2788.                 {
  2789.                 vim_free(backup);
  2790.                 backup = NULL;
  2791.                 }
  2792.             }
  2793.             }
  2794.             break;
  2795.         }
  2796.         vim_free(rootname);
  2797.  
  2798.         /*
  2799.          * Try to create the backup file
  2800.          */
  2801.         if (backup != NULL)
  2802.         {
  2803.             /* remove old backup, if present */
  2804.             mch_remove(backup);
  2805.             /* Open with O_EXCL to avoid the file being created while
  2806.              * we were sleeping (symlink hacker attack?) */
  2807.             bfd = mch_open((char *)backup,
  2808.                        O_WRONLY|O_CREAT|O_EXTRA|O_EXCL, 0666);
  2809.             if (bfd < 0)
  2810.             {
  2811.             vim_free(backup);
  2812.             backup = NULL;
  2813.             }
  2814.             else
  2815.             {
  2816.             /* set file protection same as original file, but
  2817.              * strip s-bit */
  2818.             (void)mch_setperm(backup, perm & 0777);
  2819.  
  2820. #ifdef UNIX
  2821.             /*
  2822.              * Try to set the group of the backup same as the
  2823.              * original file. If this fails, set the protection
  2824.              * bits for the group same as the protection bits for
  2825.              * others.
  2826.              */
  2827.             if (st_new.st_gid != st_old.st_gid &&
  2828. # ifdef HAVE_FCHOWN  /* sequent-ptx lacks fchown() */
  2829.                     fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
  2830. # else
  2831.               chown((char *)backup, (uid_t)-1, st_old.st_gid) != 0
  2832. # endif
  2833.                         )
  2834.                 mch_setperm(backup,
  2835.                       (perm & 0707) | ((perm & 07) << 3));
  2836. #endif
  2837.  
  2838.             /*
  2839.              * copy the file.
  2840.              */
  2841.             write_info.bw_fd = bfd;
  2842.             write_info.bw_buf = copybuf;
  2843. #ifdef HAS_BW_FLAGS
  2844.             write_info.bw_flags = FIO_NOCONVERT;
  2845. #endif
  2846.             while ((write_info.bw_len = vim_read(fd, copybuf,
  2847.                                 BUFSIZE)) > 0)
  2848.             {
  2849.                 if (buf_write_bytes(&write_info) == FAIL)
  2850.                 {
  2851.                 errmsg = (char_u *)_("Can't write to backup file (use ! to override)");
  2852.                 break;
  2853.                 }
  2854.                 ui_breakcheck();
  2855.                 if (got_int)
  2856.                 {
  2857.                 errmsg = (char_u *)_(e_interr);
  2858.                 break;
  2859.                 }
  2860.             }
  2861.  
  2862.             if (close(bfd) < 0 && errmsg == NULL)
  2863.                 errmsg = (char_u *)_("Close error for backup file (use ! to override)");
  2864.             if (write_info.bw_len < 0)
  2865.                 errmsg = (char_u *)_("Can't read file for backup (use ! to override)");
  2866. #ifdef UNIX
  2867.             set_file_time(backup, st_old.st_atime, st_old.st_mtime);
  2868. #endif
  2869. #ifdef HAVE_ACL
  2870.             mch_set_acl(backup, acl);
  2871. #endif
  2872.             break;
  2873.             }
  2874.         }
  2875.         }
  2876.     nobackup:
  2877.         close(fd);        /* ignore errors for closing read file */
  2878.         vim_free(copybuf);
  2879.  
  2880.         if (backup == NULL && errmsg == NULL)
  2881.         errmsg = (char_u *)_("Cannot create backup file (use ! to override)");
  2882.         /* ignore errors when forceit is TRUE */
  2883.         if ((some_error || errmsg != NULL) && !forceit)
  2884.         {
  2885.         retval = FAIL;
  2886.         goto fail;
  2887.         }
  2888.         errmsg = NULL;
  2889.     }
  2890.     else
  2891.     {
  2892.         char_u    *dirp;
  2893.         char_u    *p;
  2894.         char_u    *rootname;
  2895.  
  2896.         /*
  2897.          * Make a backup by renaming the original file.
  2898.          *
  2899.          * Form the backup file name - change path/fo.o.h to
  2900.          * path/fo.o.h.bak Try all directories in 'backupdir', first one
  2901.          * that works is used.
  2902.          */
  2903.         dirp = p_bdir;
  2904.         while (*dirp)
  2905.         {
  2906.         /*
  2907.          * Isolate one directory name and make the backup file name.
  2908.          */
  2909.         (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
  2910.         rootname = get_file_in_dir(fname, IObuff);
  2911.         if (rootname == NULL)
  2912.             backup = NULL;
  2913.         else
  2914.         {
  2915.             backup = buf_modname(
  2916. #ifdef SHORT_FNAME
  2917.                 TRUE,
  2918. #else
  2919.                 (buf->b_p_sn || buf->b_shortname),
  2920. #endif
  2921.                          rootname, backup_ext, FALSE);
  2922.             vim_free(rootname);
  2923.         }
  2924.  
  2925.         if (backup != NULL)
  2926.         {
  2927.             /*
  2928.              * If we are not going to keep the backup file, don't
  2929.              * delete an existing one, try to use another name.
  2930.              * Change one character, just before the extension.
  2931.              */
  2932.             if (!p_bk && mch_getperm(backup) >= 0)
  2933.             {
  2934.             p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
  2935.             if (p < backup)    /* empty file name ??? */
  2936.                 p = backup;
  2937.             *p = 'z';
  2938.             while (*p > 'a' && mch_getperm(backup) >= 0)
  2939.                 --*p;
  2940.             /* They all exist??? Must be something wrong! */
  2941.             if (*p == 'a')
  2942.             {
  2943.                 vim_free(backup);
  2944.                 backup = NULL;
  2945.             }
  2946.             }
  2947.         }
  2948.         if (backup != NULL)
  2949.         {
  2950.  
  2951.             /*
  2952.              * Delete any existing backup and move the current version to
  2953.              * the backup.    For safety, we don't remove the backup until
  2954.              * the write has finished successfully. And if the 'backup'
  2955.              * option is set, leave it around.
  2956.              */
  2957.             /*
  2958.              * If the renaming of the original file to the backup file
  2959.              * works, quit here.
  2960.              */
  2961.             if (vim_rename(fname, backup) == 0)
  2962.             break;
  2963.  
  2964.             vim_free(backup);   /* don't do the rename below */
  2965.             backup = NULL;
  2966.         }
  2967.         }
  2968.         if (backup == NULL && !forceit)
  2969.         {
  2970.         errmsg = (char_u *)_("Can't make backup file (use ! to override)");
  2971.         goto fail;
  2972.         }
  2973.     }
  2974.     }
  2975.  
  2976. #if defined(UNIX) && !defined(ARCHIE)
  2977.     /* When using ":w!" and the file was read-only: make it writable */
  2978.     if (forceit && st_old.st_uid == getuid() && perm >= 0 && !(perm & 0200)
  2979.                      && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
  2980.     {
  2981.     perm |= 0200;
  2982.     (void)mch_setperm(fname, perm);
  2983.     made_writable = TRUE;
  2984.     }
  2985. #endif
  2986.  
  2987.     /* When using ":w!" and writing to the current file, readonly makes no
  2988.      * sense, reset it */
  2989.     if (forceit && overwriting)
  2990.     {
  2991.     buf->b_p_ro = FALSE;
  2992. #ifdef FEAT_TITLE
  2993.     need_maketitle = TRUE;        /* set window title later */
  2994. #endif
  2995. #ifdef FEAT_WINDOWS
  2996.     status_redraw_all();        /* redraw status lines later */
  2997. #endif
  2998.     }
  2999.  
  3000.     if (end > buf->b_ml.ml_line_count)
  3001.     end = buf->b_ml.ml_line_count;
  3002.     if (buf->b_ml.ml_flags & ML_EMPTY)
  3003.     start = end + 1;
  3004.  
  3005.     /*
  3006.      * If the original file is being overwritten, there is a small chance that
  3007.      * we crash in the middle of writing. Therefore the file is preserved now.
  3008.      * This makes all block numbers positive so that recovery does not need
  3009.      * the original file.
  3010.      * Don't do this if there is a backup file and we are exiting.
  3011.      */
  3012.     if (reset_changed && !newfile && !otherfile(ffname)
  3013.                           && !(exiting && backup != NULL))
  3014.     {
  3015.     ml_preserve(buf, FALSE);
  3016.     if (got_int)
  3017.     {
  3018.         errmsg = (char_u *)_(e_interr);
  3019.         goto fail;
  3020.     }
  3021.     }
  3022.  
  3023. #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
  3024.     /*
  3025.      * Before risking to lose the original file verify if there's
  3026.      * a resource fork to preserve, and if cannot be done warn
  3027.      * the users. This happens when overwriting without backups.
  3028.      */
  3029.     if (backup == NULL && overwriting && !append)
  3030.     if (mch_has_resource_fork(fname))
  3031.     {
  3032.         errmsg = (char_u *)_("The resource fork will be lost (use ! to override)");
  3033.         goto fail;
  3034.     }
  3035. #endif
  3036.  
  3037. #ifdef VMS
  3038.     STRCPY(nfname, fname);
  3039.     vms_remove_version(nfname); /* remove version */
  3040.     fname = nfname;
  3041. #endif
  3042.     /* Default: write the the file directly.  May write to a temp file for
  3043.      * multi-byte conversion. */
  3044.     wfname = fname;
  3045.  
  3046. #ifdef FEAT_MBYTE
  3047.     /* Check for forced 'fileencoding' from "++opt=val" argument. */
  3048.     if (eap != NULL && eap->force_enc != 0)
  3049.     {
  3050.     fenc = eap->cmd + eap->force_enc;
  3051.     fenc = enc_canonize(fenc);
  3052.     fenc_tofree = fenc;
  3053.     }
  3054.     else
  3055.     fenc = buf->b_p_fenc;
  3056.  
  3057.     /*
  3058.      * The file needs to be converted when 'fileencoding' is set and
  3059.      * 'fileencoding' differs from 'encoding'.
  3060.      */
  3061.     converted = (*fenc != NUL && !same_encoding(p_enc, fenc));
  3062.  
  3063.     /*
  3064.      * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done.  Or
  3065.      * Latin1 to Unicode conversion.  This is handled in buf_write_bytes().
  3066.      * Prepare the flags for it and allocate bw_conv_buf when needed.
  3067.      */
  3068.     if (converted && (enc_utf8 || !has_mbyte))
  3069.     {
  3070.     wb_flags = get_fio_flags(fenc);
  3071.     if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
  3072.     {
  3073.         /* Need to allocate a buffer to translate into. */
  3074.         if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
  3075.         write_info.bw_conv_buflen = bufsize * 2;
  3076.         else /* FIO_UCS4 */
  3077.         write_info.bw_conv_buflen = bufsize * 4;
  3078.         write_info.bw_conv_buf
  3079.                = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
  3080.         if (write_info.bw_conv_buf == NULL)
  3081.         end = 0;
  3082.     }
  3083.     }
  3084.  
  3085. # if defined(FEAT_EVAL) || defined(USE_ICONV)
  3086.     if (converted && wb_flags == 0)
  3087.     {
  3088. #  ifdef USE_ICONV
  3089.     /*
  3090.      * Use iconv() conversion when conversion is needed and it's not done
  3091.      * internally.
  3092.      */
  3093.     write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
  3094.                     enc_utf8 ? (char_u *)"utf-8" : p_enc);
  3095.     if (write_info.bw_iconv_fd != (iconv_t)-1)
  3096.     {
  3097.         /* We're going to use iconv(), allocate a buffer to convert in. */
  3098.         write_info.bw_conv_buflen = bufsize * ICONV_MULT;
  3099.         write_info.bw_conv_buf
  3100.                = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
  3101.         if (write_info.bw_conv_buf == NULL)
  3102.         end = 0;
  3103.         write_info.bw_first = TRUE;
  3104.     }
  3105. #   ifdef FEAT_EVAL
  3106.     else
  3107. #   endif
  3108. #  endif
  3109.  
  3110. #  ifdef FEAT_EVAL
  3111.         /*
  3112.          * When the file needs to be converted with 'charconvert' after
  3113.          * writing, write to a temp file instead and let the conversion
  3114.          * overwrite the original file.
  3115.          */
  3116.         if (*p_ccv != NUL)
  3117.         {
  3118.         wfname = vim_tempname('w');
  3119.         if (wfname == NULL)    /* Can't write without a tempfile! */
  3120.         {
  3121.             errmsg = (char_u *)_("E214: Can't find temp file for writing");
  3122.             goto fail;
  3123.         }
  3124.         }
  3125. #  endif
  3126.     }
  3127. # endif
  3128.     if (converted && wb_flags == 0
  3129. #  ifdef USE_ICONV
  3130.         && write_info.bw_iconv_fd == (iconv_t)-1
  3131. #  endif
  3132. #  ifdef FEAT_EVAL
  3133.         && wfname == fname
  3134. #  endif
  3135.         )
  3136.     {
  3137.     if (!forceit)
  3138.     {
  3139.         errmsg = (char_u *)_("E213: Cannot convert (use ! to write without conversion)");
  3140.         goto fail;
  3141.     }
  3142.     notconverted = TRUE;
  3143.     }
  3144. #endif
  3145.  
  3146.     /*
  3147.      * Open the file "wfname" for writing.
  3148.      * We may try to open the file twice: If we can't write to the
  3149.      * file and forceit is TRUE we delete the existing file and try to create
  3150.      * a new one. If this still fails we may have lost the original file!
  3151.      * (this may happen when the user reached his quotum for number of files).
  3152.      * Appending will fail if the file does not exist and forceit is FALSE.
  3153.      */
  3154.     while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
  3155.             ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
  3156.             : (O_CREAT | O_TRUNC))
  3157.             , 0666)) < 0)
  3158.     {
  3159.     struct stat st;
  3160.  
  3161.     /*
  3162.      * A forced write will try to create a new file if the old one is
  3163.      * still readonly. This may also happen when the directory is
  3164.      * read-only. In that case the mch_remove() will fail.
  3165.      */
  3166.     if (errmsg == NULL)
  3167.     {
  3168. #ifdef UNIX
  3169.         struct stat    st;
  3170.  
  3171.         /* Don't delete the file when it's a hard or symbolic link. */
  3172.         if ((!newfile && st_old.st_nlink > 1)
  3173.             || (mch_lstat((char *)fname, &st) == 0
  3174.             && (st.st_dev != st_old.st_dev
  3175.                 || st.st_ino != st_old.st_ino)))
  3176.         errmsg = (char_u *)_("E166: Can't open linked file for writing");
  3177.         else
  3178. #endif
  3179.         {
  3180.         errmsg = (char_u *)_("E212: Can't open file for writing");
  3181.         if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
  3182.                                  && perm >= 0)
  3183.         {
  3184. #ifdef UNIX
  3185.             /* we write to the file, thus it should be marked
  3186.                writable after all */
  3187.             if (!(perm & 0200))
  3188.             made_writable = TRUE;
  3189.             perm |= 0200;
  3190.             if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
  3191.             perm &= 0777;
  3192. #endif
  3193.             if (!append)        /* don't remove when appending */
  3194.             mch_remove(wfname);
  3195.             continue;
  3196.         }
  3197.         }
  3198.     }
  3199.     /*
  3200.      * If we failed to open the file, we don't need a backup. Throw it
  3201.      * away.  If we moved or removed the original file try to put the
  3202.      * backup in its place.
  3203.      */
  3204.     if (backup != NULL && wfname == fname)
  3205.     {
  3206.         if (backup_copy)
  3207.         {
  3208.         /*
  3209.          * There is a small chance that we removed the original, try
  3210.          * to move the copy in its place.
  3211.          * This may not work if the vim_rename() fails.
  3212.          * In that case we leave the copy around.
  3213.          */
  3214.         /* If file does not exist, put the copy in its place */
  3215.         if (mch_stat((char *)fname, &st) < 0)
  3216.             vim_rename(backup, fname);
  3217.         /* if original file does exist throw away the copy */
  3218.         if (mch_stat((char *)fname, &st) >= 0)
  3219.             mch_remove(backup);
  3220.         }
  3221.         else
  3222.         {
  3223.         /* try to put the original file back */
  3224.         vim_rename(backup, fname);
  3225.         }
  3226.     }
  3227.  
  3228.     /* if original file no longer exists give an extra warning */
  3229.     if (!newfile && mch_stat((char *)fname, &st) < 0)
  3230.         end = 0;
  3231.  
  3232. #ifdef FEAT_MBYTE
  3233.     if (wfname != fname)
  3234.         vim_free(wfname);
  3235. #endif
  3236.     goto fail;
  3237.     }
  3238.     errmsg = NULL;
  3239.  
  3240. #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
  3241.     /*
  3242.      * On macintosh copy the original files attributes (i.e. the backup)
  3243.      * This is done in order to preserve the ressource fork and the
  3244.      * Finder attribute (label, comments, custom icons, file creatore)
  3245.      */
  3246.     if (backup != NULL && overwriting && !append)
  3247.     {
  3248.     if (backup_copy)
  3249.         (void)mch_copy_file_attribute(wfname, backup);
  3250.     else
  3251.         (void)mch_copy_file_attribute(backup, wfname);
  3252.     }
  3253.  
  3254.     if (!overwriting && !append)
  3255.     {
  3256.     if (buf->b_ffname != NULL)
  3257.         (void)mch_copy_file_attribute(buf->b_ffname, wfname);
  3258.     /* Should copy ressource fork */
  3259.     }
  3260. #endif
  3261.  
  3262.     write_info.bw_fd = fd;
  3263.  
  3264. #ifdef FEAT_CRYPT
  3265.     if (*buf->b_p_key)
  3266.     {
  3267.     crypt_init_keys(buf->b_p_key);
  3268.     /* Write magic number, so that Vim knows that this file is encrypted
  3269.      * when reading it again.  This also undergoes utf-8 to ucs-2/4
  3270.      * conversion when needed. */
  3271.     write_info.bw_buf = (char_u *)CRYPT_MAGIC;
  3272.     write_info.bw_len = CRYPT_MAGIC_LEN;
  3273.     write_info.bw_flags = FIO_NOCONVERT;
  3274.     if (buf_write_bytes(&write_info) == FAIL)
  3275.         end = 0;
  3276.     wb_flags |= FIO_ENCRYPTED;
  3277.     }
  3278. #endif
  3279.  
  3280.     write_info.bw_buf = buffer;
  3281.     nchars = 0;
  3282.  
  3283. #ifdef FEAT_MBYTE
  3284.     /*
  3285.      * The BOM is written just after the encryption magic number.
  3286.      */
  3287.     if (buf->b_p_bomb && !buf->b_p_bin)
  3288.     {
  3289.     write_info.bw_len = make_bom(buffer, fenc);
  3290.     if (write_info.bw_len > 0)
  3291.     {
  3292.         /* don't convert, do encryption */
  3293.         write_info.bw_flags = FIO_NOCONVERT | wb_flags;
  3294.         if (buf_write_bytes(&write_info) == FAIL)
  3295.         end = 0;
  3296.         else
  3297.         nchars += write_info.bw_len;
  3298.     }
  3299.     }
  3300. #endif
  3301.  
  3302.     write_info.bw_len = bufsize;
  3303. #ifdef HAS_BW_FLAGS
  3304.     write_info.bw_flags = wb_flags;
  3305. #endif
  3306.     fileformat = get_fileformat_force(buf, eap);
  3307.     s = buffer;
  3308.     len = 0;
  3309.     for (lnum = start; lnum <= end; ++lnum)
  3310.     {
  3311.     /*
  3312.      * The next while loop is done once for each character written.
  3313.      * Keep it fast!
  3314.      */
  3315.     ptr = ml_get_buf(buf, lnum, FALSE) - 1;
  3316.     while ((c = *++ptr) != NUL)
  3317.     {
  3318.         if (c == NL)
  3319.         *s = NUL;        /* replace newlines with NULs */
  3320.         else if (c == CR && fileformat == EOL_MAC)
  3321.         *s = NL;        /* Mac: replace CRs with NLs */
  3322.         else
  3323.         *s = c;
  3324.         ++s;
  3325.         if (++len != bufsize)
  3326.         continue;
  3327.         if (buf_write_bytes(&write_info) == FAIL)
  3328.         {
  3329.         end = 0;        /* write error: break loop */
  3330.         break;
  3331.         }
  3332.         nchars += bufsize;
  3333.         s = buffer;
  3334.         len = 0;
  3335.     }
  3336.     /* write failed or last line has no EOL: stop here */
  3337.     if (end == 0
  3338.         || (lnum == end
  3339.             && buf->b_p_bin
  3340.             && (lnum == write_no_eol_lnum
  3341.             || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
  3342.     {
  3343.         ++lnum;            /* written the line, count it */
  3344.         no_eol = TRUE;
  3345.         break;
  3346.     }
  3347.     if (fileformat == EOL_UNIX)
  3348.         *s++ = NL;
  3349.     else
  3350.     {
  3351.         *s++ = CR;            /* EOL_MAC or EOL_DOS: write CR */
  3352.         if (fileformat == EOL_DOS)    /* write CR-NL */
  3353.         {
  3354.         if (++len == bufsize)
  3355.         {
  3356.             if (buf_write_bytes(&write_info) == FAIL)
  3357.             {
  3358.             end = 0;    /* write error: break loop */
  3359.             break;
  3360.             }
  3361.             nchars += bufsize;
  3362.             s = buffer;
  3363.             len = 0;
  3364.         }
  3365.         *s++ = NL;
  3366.         }
  3367.     }
  3368.     if (++len == bufsize && end)
  3369.     {
  3370.         if (buf_write_bytes(&write_info) == FAIL)
  3371.         {
  3372.         end = 0;        /* write error: break loop */
  3373.         break;
  3374.         }
  3375.         nchars += bufsize;
  3376.         s = buffer;
  3377.         len = 0;
  3378.  
  3379.         ui_breakcheck();
  3380.         if (got_int)
  3381.         {
  3382.         end = 0;        /* Interrupted, break loop */
  3383.         break;
  3384.         }
  3385.     }
  3386. #ifdef VMS
  3387.     /*
  3388.      * On VMS there is a problem: newlines get added when writing blocks
  3389.      * at a time. Fix it by writing a line at a time.
  3390.      * This is much slower!
  3391.      * Explanation: Vim can not handle, so far, variable record format.
  3392.      * With $analize/rms filename you can get the rms file structure, and
  3393.      * if the Record format filed is variable, CR will be added after
  3394.      * every written buffer.  In other cases it works without this fix.
  3395.      * From other side read is about 5 times slower for "variable record
  3396.      * format" files.
  3397.      */
  3398.     if (buf->b_fab_rfm == FAB$C_VAR)
  3399.     {
  3400.         write_info.bw_len = len;
  3401.         if (buf_write_bytes(&write_info) == FAIL)
  3402.         {
  3403.         end = 0;        /* write error: break loop */
  3404.         break;
  3405.         }
  3406.         write_info.bw_len = bufsize;
  3407.         nchars += len;
  3408.         s = buffer;
  3409.         len = 0;
  3410.     }
  3411. #endif
  3412.     }
  3413.     if (len > 0 && end > 0)
  3414.     {
  3415.     write_info.bw_len = len;
  3416.     if (buf_write_bytes(&write_info) == FAIL)
  3417.         end = 0;            /* write error */
  3418.     nchars += len;
  3419.     }
  3420.  
  3421.     if (close(fd) != 0)
  3422.     {
  3423.     errmsg = (char_u *)_("Close failed");
  3424.     end = 0;
  3425.     }
  3426.  
  3427. #ifdef UNIX
  3428.     if (made_writable)
  3429.     perm &= ~0200;        /* reset 'w' bit for security reasons */
  3430. #endif
  3431.     if (perm >= 0)        /* set perm. of new file same as old file */
  3432.     (void)mch_setperm(wfname, perm);
  3433. #ifdef RISCOS
  3434.     if (!append && !filtering)
  3435.     /* Set the filetype after writing the file. */
  3436.     mch_set_filetype(wfname, buf->b_p_oft);
  3437. #endif
  3438. #ifdef HAVE_ACL
  3439.     if (!backup_copy)
  3440.     mch_set_acl(wfname, acl);
  3441. #endif
  3442.  
  3443. #ifdef UNIX
  3444.     /* When creating a new file, set its owner/group to that of the original
  3445.      * file.  Get the new device and inode number. */
  3446.     if (backup != NULL && !backup_copy)
  3447.     {
  3448.     chown((char *)wfname, st_old.st_uid, st_old.st_gid);
  3449.     buf_setino(buf);
  3450.     }
  3451. #endif
  3452.  
  3453.  
  3454. #if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
  3455.     if (wfname != fname)
  3456.     {
  3457.     /*
  3458.      * The file was written to a temp file, now it needs to be converted
  3459.      * with 'charconvert' to (overwrite) the output file.
  3460.      */
  3461.     if (end != 0)
  3462.     {
  3463.         if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
  3464.                                wfname, fname) == FAIL)
  3465.         {
  3466.         write_info.bw_conv_error = TRUE;
  3467.         end = 0;
  3468.         }
  3469.     }
  3470.     mch_remove(wfname);
  3471.     vim_free(wfname);
  3472.     }
  3473. #endif
  3474.  
  3475.     if (end == 0)
  3476.     {
  3477.     if (errmsg == NULL)
  3478.     {
  3479. #ifdef FEAT_MBYTE
  3480.         if (write_info.bw_conv_error)
  3481.         errmsg = (char_u *)_("write error, conversion failed");
  3482.         else
  3483. #endif
  3484.         if (got_int)
  3485.             errmsg = (char_u *)_(e_interr);
  3486.         else
  3487.             errmsg = (char_u *)_("write error (file system full?)");
  3488.     }
  3489.  
  3490.     /*
  3491.      * If we have a backup file, try to put it in place of the new file,
  3492.      * because the new file is probably corrupt.  This avoids loosing the
  3493.      * original file when trying to make a backup when writing the file a
  3494.      * second time.
  3495.      * When "backup_copy" is set we need to copy the backup over the new
  3496.      * file.  Otherwise rename the backup file.
  3497.      * If this is OK, don't give the extra warning message.
  3498.      */
  3499.     if (backup != NULL)
  3500.     {
  3501.         if (backup_copy)
  3502.         {
  3503.         /* This may take a while, if we were interrupted let the user
  3504.          * know we got the message. */
  3505.         if (got_int)
  3506.         {
  3507.             MSG(_(e_interr));
  3508.             out_flush();
  3509.         }
  3510.         if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
  3511.         {
  3512.             if ((write_info.bw_fd = mch_open((char *)fname,
  3513.               O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA, 0666)) >= 0)
  3514.             {
  3515.             /* copy the file. */
  3516.             write_info.bw_buf = smallbuf;
  3517. #ifdef HAS_BW_FLAGS
  3518.             write_info.bw_flags = FIO_NOCONVERT;
  3519. #endif
  3520.             while ((write_info.bw_len = vim_read(fd, smallbuf,
  3521.                               SMBUFSIZE)) > 0)
  3522.                 if (buf_write_bytes(&write_info) == FAIL)
  3523.                 break;
  3524.  
  3525.             if (close(write_info.bw_fd) >= 0
  3526.                            && write_info.bw_len == 0)
  3527.                 end = 1;        /* success */
  3528.             }
  3529.             close(fd);    /* ignore errors for closing read file */
  3530.         }
  3531.         }
  3532.         else
  3533.         {
  3534.         if (vim_rename(backup, fname) == 0)
  3535.             end = 1;
  3536.         }
  3537.     }
  3538.     goto fail;
  3539.     }
  3540.  
  3541.     lnum -= start;        /* compute number of written lines */
  3542.     --no_wait_return;        /* may wait for return now */
  3543.  
  3544. #ifndef UNIX
  3545. # ifdef VMS
  3546.     STRCPY(nfname, sfname);
  3547.     vms_remove_version(nfname); /* remove version */
  3548.     fname = nfname;
  3549. # else
  3550.     fname = sfname;        /* use shortname now, for the messages */
  3551. # endif
  3552. #endif
  3553.     if (!filtering)
  3554.     {
  3555.     msg_add_fname(buf, fname);    /* put fname in IObuff with quotes */
  3556.     c = FALSE;
  3557. #ifdef FEAT_MBYTE
  3558.     if (write_info.bw_conv_error)
  3559.     {
  3560.         STRCAT(IObuff, _(" CONVERSION ERROR"));
  3561.         c = TRUE;
  3562.     }
  3563.     else if (notconverted)
  3564.     {
  3565.         STRCAT(IObuff, _("[NOT converted]"));
  3566.         c = TRUE;
  3567.     }
  3568.     else if (converted)
  3569.     {
  3570.         STRCAT(IObuff, _("[converted]"));
  3571.         c = TRUE;
  3572.     }
  3573. #endif
  3574.     if (device)
  3575.     {
  3576.         STRCAT(IObuff, _("[Device]"));
  3577.         c = TRUE;
  3578.     }
  3579.     else if (newfile)
  3580.     {
  3581.         STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
  3582.         c = TRUE;
  3583.     }
  3584.     if (no_eol)
  3585.     {
  3586.         msg_add_eol();
  3587.         c = TRUE;
  3588.     }
  3589.     /* may add [unix/dos/mac] */
  3590.     if (msg_add_fileformat(fileformat))
  3591.         c = TRUE;
  3592. #ifdef FEAT_CRYPT
  3593.     if (wb_flags & FIO_ENCRYPTED)
  3594.     {
  3595.         STRCAT(IObuff, _("[crypted]"));
  3596.         c = TRUE;
  3597.     }
  3598. #endif
  3599.     msg_add_lines(c, (long)lnum, nchars);    /* add line/char count */
  3600.     if (!shortmess(SHM_WRITE))
  3601.     {
  3602.         if (append)
  3603.         STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
  3604.         else
  3605.         STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
  3606.     }
  3607.  
  3608.     set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0));
  3609.     keep_msg_attr = 0;
  3610.     }
  3611.  
  3612.     if (reset_changed && whole
  3613. #ifdef FEAT_MBYTE
  3614.         && !write_info.bw_conv_error
  3615. #endif
  3616.         )        /* when written everything correctly */
  3617.     {
  3618.     unchanged(buf, TRUE);
  3619.     u_unchanged(buf);
  3620.     }
  3621.  
  3622.     /*
  3623.      * If written to the current file, update the timestamp of the swap file
  3624.      * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
  3625.      */
  3626.     if (!exiting && overwriting)
  3627.     {
  3628.     ml_timestamp(buf);
  3629.     buf->b_flags &= ~BF_WRITE_MASK;
  3630.     }
  3631.  
  3632.     /*
  3633.      * If we kept a backup until now, and we are in patch mode, then we make
  3634.      * the backup file our 'original' file.
  3635.      */
  3636.     if (*p_pm && dobackup)
  3637.     {
  3638.     char *org = (char *)buf_modname(
  3639. #ifdef SHORT_FNAME
  3640.                     TRUE,
  3641. #else
  3642.                     (buf->b_p_sn || buf->b_shortname),
  3643. #endif
  3644.                               fname, p_pm, FALSE);
  3645.  
  3646.     if (backup != NULL)
  3647.     {
  3648.         struct stat st;
  3649.  
  3650.         /*
  3651.          * If the original file does not exist yet
  3652.          * the current backup file becomes the original file
  3653.          */
  3654.         if (org == NULL)
  3655.         EMSG(_("E205: Patchmode: can't save original file"));
  3656.         else if (mch_stat(org, &st) < 0)
  3657.         {
  3658.         vim_rename(backup, (char_u *)org);
  3659.         vim_free(backup);        /* don't delete the file */
  3660.         backup = NULL;
  3661. #ifdef UNIX
  3662.         set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
  3663. #endif
  3664.         }
  3665.     }
  3666.     /*
  3667.      * If there is no backup file, remember that a (new) file was
  3668.      * created.
  3669.      */
  3670.     else
  3671.     {
  3672.         int empty_fd;
  3673.  
  3674.         if (org == NULL
  3675.             || (empty_fd = mch_open(org, O_CREAT | O_EXTRA | O_EXCL,
  3676.                                    0666)) < 0)
  3677.           EMSG(_("E206: patchmode: can't touch empty original file"));
  3678.         else
  3679.           close(empty_fd);
  3680.     }
  3681.     if (org != NULL)
  3682.     {
  3683.         mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
  3684.         vim_free(org);
  3685.     }
  3686.     }
  3687.  
  3688.     /*
  3689.      * Remove the backup unless 'backup' option is set
  3690.      */
  3691.     if (!p_bk && backup != NULL && mch_remove(backup) != 0)
  3692.     EMSG(_("E207: Can't delete backup file"));
  3693.  
  3694. #ifdef FEAT_SUN_WORKSHOP
  3695.     if (usingSunWorkShop)
  3696.     workshop_file_saved((char *) ffname);
  3697. #endif
  3698.  
  3699.     goto nofail;
  3700.  
  3701.     /*
  3702.      * Finish up.  We get here either after failure or success.
  3703.      */
  3704. fail:
  3705.     --no_wait_return;        /* may wait for return now */
  3706. nofail:
  3707.  
  3708.     vim_free(backup);
  3709.     if (buffer != smallbuf)
  3710.     vim_free(buffer);
  3711. #ifdef FEAT_MBYTE
  3712.     vim_free(fenc_tofree);
  3713.     vim_free(write_info.bw_conv_buf);
  3714. # ifdef USE_ICONV
  3715.     if (write_info.bw_iconv_fd != (iconv_t)-1)
  3716.     {
  3717.     iconv_close(write_info.bw_iconv_fd);
  3718.     write_info.bw_iconv_fd = (iconv_t)-1;
  3719.     }
  3720. # endif
  3721. #endif
  3722. #ifdef HAVE_ACL
  3723.     mch_free_acl(acl);
  3724. #endif
  3725.  
  3726.     if (errmsg != NULL)
  3727.     {
  3728.     attr = hl_attr(HLF_E);    /* set highlight for error messages */
  3729.     msg_add_fname(buf,
  3730. #ifndef UNIX
  3731.         sfname
  3732. #else
  3733.         fname
  3734. #endif
  3735.              );        /* put file name in IObuff with quotes */
  3736.     if (STRLEN(IObuff) + STRLEN(errmsg) >= IOSIZE)
  3737.         IObuff[IOSIZE - STRLEN(errmsg) - 1] = NUL;
  3738.     STRCAT(IObuff, errmsg);
  3739.     emsg(IObuff);
  3740.  
  3741.     retval = FAIL;
  3742.     if (end == 0)
  3743.     {
  3744.         MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
  3745.             attr | MSG_HIST);
  3746.         MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
  3747.             attr | MSG_HIST);
  3748.  
  3749.         /* Update the timestamp to avoid an "overwrite changed file"
  3750.          * prompt when writing again. */
  3751.         if (mch_stat((char *)fname, &st_old) >= 0)
  3752.         {
  3753.         buf_store_time(buf, &st_old, fname);
  3754.         buf->b_mtime_read = buf->b_mtime;
  3755.         }
  3756.     }
  3757.     }
  3758.     msg_scroll = msg_save;
  3759.  
  3760. #ifdef FEAT_AUTOCMD
  3761.     if (!got_int)
  3762.     {
  3763.     aco_save_T    aco;
  3764.  
  3765.     write_no_eol_lnum = 0;    /* in case it was set by the previous read */
  3766.  
  3767.     /*
  3768.      * Apply POST autocommands.
  3769.      * Careful: The autocommands may call buf_write() recursively!
  3770.      */
  3771.     aucmd_prepbuf(&aco, buf);
  3772.  
  3773.     if (append)
  3774.         apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
  3775.                               FALSE, curbuf, eap);
  3776.     else if (filtering)
  3777.         apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
  3778.                               FALSE, curbuf, eap);
  3779.     else if (reset_changed && whole)
  3780.         apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
  3781.                               FALSE, curbuf, eap);
  3782.     else
  3783.         apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
  3784.                               FALSE, curbuf, eap);
  3785.  
  3786.     /* restore curwin/curbuf and a few other things */
  3787.     aucmd_restbuf(&aco);
  3788.     }
  3789. #endif
  3790.  
  3791.     got_int |= prev_got_int;
  3792.  
  3793. #ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
  3794.     /* Update machine specific information. */
  3795.     mch_post_buffer_write(buf);
  3796. #endif
  3797.     return retval;
  3798. }
  3799.  
  3800. /*
  3801.  * Put file name into IObuff with quotes.
  3802.  */
  3803.     static void
  3804. msg_add_fname(buf, fname)
  3805.     buf_T    *buf;
  3806.     char_u    *fname;
  3807. {
  3808.     if (fname == NULL)
  3809.     fname = (char_u *)"-stdin-";
  3810.     home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
  3811.     IObuff[0] = '"';
  3812.     STRCAT(IObuff, "\" ");
  3813. }
  3814.  
  3815. /*
  3816.  * Append message for text mode to IObuff.
  3817.  * Return TRUE if something appended.
  3818.  */
  3819.     static int
  3820. msg_add_fileformat(eol_type)
  3821.     int        eol_type;
  3822. {
  3823. #ifndef USE_CRNL
  3824.     if (eol_type == EOL_DOS)
  3825.     {
  3826.     STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
  3827.     return TRUE;
  3828.     }
  3829. #endif
  3830. #ifndef USE_CR
  3831.     if (eol_type == EOL_MAC)
  3832.     {
  3833.     STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
  3834.     return TRUE;
  3835.     }
  3836. #endif
  3837. #if defined(USE_CRNL) || defined(USE_CR)
  3838.     if (eol_type == EOL_UNIX)
  3839.     {
  3840.     STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
  3841.     return TRUE;
  3842.     }
  3843. #endif
  3844.     return FALSE;
  3845. }
  3846.  
  3847. /*
  3848.  * Append line and character count to IObuff.
  3849.  */
  3850.     static void
  3851. msg_add_lines(insert_space, lnum, nchars)
  3852.     int        insert_space;
  3853.     long    lnum;
  3854.     long    nchars;
  3855. {
  3856.     char_u  *p;
  3857.  
  3858.     p = IObuff + STRLEN(IObuff);
  3859.  
  3860.     if (insert_space)
  3861.     *p++ = ' ';
  3862.     if (shortmess(SHM_LINES))
  3863.     sprintf((char *)p, "%ldL, %ldC", lnum, nchars);
  3864.     else
  3865.     {
  3866.     if (lnum == 1)
  3867.         STRCPY(p, _("1 line, "));
  3868.     else
  3869.         sprintf((char *)p, _("%ld lines, "), lnum);
  3870.     p += STRLEN(p);
  3871.     if (nchars == 1)
  3872.         STRCPY(p, _("1 character"));
  3873.     else
  3874.         sprintf((char *)p, _("%ld characters"), nchars);
  3875.     }
  3876. }
  3877.  
  3878. /*
  3879.  * Append message for missing line separator to IObuff.
  3880.  */
  3881.     static void
  3882. msg_add_eol()
  3883. {
  3884.     STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
  3885. }
  3886.  
  3887. /*
  3888.  * Check modification time of file, before writing to it.
  3889.  * The size isn't checked, because using a tool like "gzip" takes care of
  3890.  * using the same timestamp but can't set the size.
  3891.  */
  3892.     static int
  3893. check_mtime(buf, st)
  3894.     buf_T        *buf;
  3895.     struct stat        *st;
  3896. {
  3897.     if (buf->b_mtime_read != 0
  3898.         && time_differs((long)st->st_mtime, buf->b_mtime_read))
  3899.     {
  3900.     msg_scroll = TRUE;        /* don't overwrite messages here */
  3901.     msg_silent = 0;            /* must give this prompt */
  3902.     /* don't use emsg() here, don't want to flush the buffers */
  3903.     MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
  3904.                                hl_attr(HLF_E));
  3905.     if (ask_yesno((char_u *)_("Do you really want to write to it"),
  3906.                                  TRUE) == 'n')
  3907.         return FAIL;
  3908.     msg_scroll = FALSE;        /* always overwrite the file message now */
  3909.     }
  3910.     return OK;
  3911. }
  3912.  
  3913.     static int
  3914. time_differs(t1, t2)
  3915.     long    t1, t2;
  3916. {
  3917. #if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
  3918.     /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
  3919.      * the seconds.  Since the roundoff is done when flushing the inode, the
  3920.      * time may change unexpectedly by one second!!! */
  3921.     return (t1 - t2 > 1 || t2 - t1 > 1);
  3922. #else
  3923.     return (t1 != t2);
  3924. #endif
  3925. }
  3926.  
  3927. /*
  3928.  * Call write() to write a number of bytes to the file.
  3929.  * Also handles encryption and 'encoding' conversion.
  3930.  *
  3931.  * Return FAIL for failure, OK otherwise.
  3932.  */
  3933.     static int
  3934. buf_write_bytes(ip)
  3935.     struct bw_info *ip;
  3936. {
  3937.     int        wlen;
  3938.     char_u    *buf = ip->bw_buf;    /* data to write */
  3939.     int        len = ip->bw_len;    /* length of data */
  3940. #ifdef HAS_BW_FLAGS
  3941.     int        flags = ip->bw_flags;    /* extra flags */
  3942. #endif
  3943.  
  3944. #ifdef FEAT_MBYTE
  3945.     /*
  3946.      * Skip conversion when writing the crypt magic number or the BOM.
  3947.      */
  3948.     if (!(flags & FIO_NOCONVERT))
  3949.     {
  3950.     char_u        *p;
  3951.     unsigned    c;
  3952.     int        n;
  3953.  
  3954.     if (flags & FIO_UTF8)
  3955.     {
  3956.         /*
  3957.          * Convert latin1 in the buffer to UTF-8 in the file.
  3958.          */
  3959.         p = ip->bw_conv_buf;    /* translate to buffer */
  3960.         for (wlen = 0; wlen < len; ++wlen)
  3961.         p += utf_char2bytes(buf[wlen], p);
  3962.         buf = ip->bw_conv_buf;
  3963.         len = (int)(p - ip->bw_conv_buf);
  3964.     }
  3965.     else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
  3966.     {
  3967.         /*
  3968.          * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
  3969.          * Latin1 chars in the file.
  3970.          */
  3971.         if (flags & FIO_LATIN1)
  3972.         p = buf;    /* translate in-place (can only get shorter) */
  3973.         else
  3974.         p = ip->bw_conv_buf;    /* translate to buffer */
  3975.         for (wlen = 0; wlen < len; wlen += n)
  3976.         {
  3977.         if (wlen == 0 && ip->bw_restlen != 0)
  3978.         {
  3979.             int        l;
  3980.  
  3981.             /* Use remainder of previous call.  Append the start of
  3982.              * buf[] to get a full sequence.  Might still be too
  3983.              * short! */
  3984.             l = CONV_RESTLEN - ip->bw_restlen;
  3985.             if (l > len)
  3986.             l = len;
  3987.             mch_memmove(ip->bw_rest + ip->bw_restlen, buf, l);
  3988.             n = utf_ptr2len_check_len(ip->bw_rest, ip->bw_restlen + l);
  3989.             if (n > ip->bw_restlen + len)
  3990.             {
  3991.             /* We have an incomplete byte sequence at the end to
  3992.              * be written.  We can't convert it without the
  3993.              * remaining bytes.  Keep them for the next call. */
  3994.             if (ip->bw_restlen + len > CONV_RESTLEN)
  3995.                 return FAIL;
  3996.             ip->bw_restlen += len;
  3997.             break;
  3998.             }
  3999.             if (n > 1)
  4000.             c = utf_ptr2char(ip->bw_rest);
  4001.             else
  4002.             c = ip->bw_rest[0];
  4003.             if (n >= ip->bw_restlen)
  4004.             {
  4005.             n -= ip->bw_restlen;
  4006.             ip->bw_restlen = 0;
  4007.             }
  4008.             else
  4009.             {
  4010.             ip->bw_restlen -= n;
  4011.             mch_memmove(ip->bw_rest, ip->bw_rest + n,
  4012.                                  ip->bw_restlen);
  4013.             n = 0;
  4014.             }
  4015.         }
  4016.         else
  4017.         {
  4018.             n = utf_ptr2len_check_len(buf + wlen, len - wlen);
  4019.             if (n > len - wlen)
  4020.             {
  4021.             /* We have an incomplete byte sequence at the end to
  4022.              * be written.  We can't convert it without the
  4023.              * remaining bytes.  Keep them for the next call. */
  4024.             if (len - wlen > CONV_RESTLEN)
  4025.                 return FAIL;
  4026.             ip->bw_restlen = len - wlen;
  4027.             mch_memmove(ip->bw_rest, buf + wlen, ip->bw_restlen);
  4028.             break;
  4029.             }
  4030.             if (n > 1)
  4031.             c = utf_ptr2char(buf + wlen);
  4032.             else
  4033.             c = buf[wlen];
  4034.         }
  4035.  
  4036.         ip->bw_conv_error |= ucs2bytes(c, &p, flags);
  4037.         }
  4038.         if (flags & FIO_LATIN1)
  4039.         len = (int)(p - buf);
  4040.         else
  4041.         {
  4042.         buf = ip->bw_conv_buf;
  4043.         len = (int)(p - ip->bw_conv_buf);
  4044.         }
  4045.     }
  4046.  
  4047. # ifdef USE_ICONV
  4048.     if (ip->bw_iconv_fd != (iconv_t)-1)
  4049.     {
  4050.         const char    *from;
  4051.         size_t    fromlen;
  4052.         char    *to;
  4053.         size_t    tolen;
  4054.  
  4055.         /* Convert with iconv(). */
  4056.         if (ip->bw_restlen > 0)
  4057.         {
  4058.         /* Need to concatenate the remainder of the previous call and
  4059.          * the bytes of the current call.  Use the end of the
  4060.          * conversion buffer for this. */
  4061.         fromlen = len + ip->bw_restlen;
  4062.         from = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
  4063.         mch_memmove((void *)from, ip->bw_rest, (size_t)ip->bw_restlen);
  4064.         mch_memmove((void *)(from + ip->bw_restlen), buf, (size_t)len);
  4065.         tolen = ip->bw_conv_buflen - fromlen;
  4066.         }
  4067.         else
  4068.         {
  4069.         from = (const char *)buf;
  4070.         fromlen = len;
  4071.         tolen = ip->bw_conv_buflen;
  4072.         }
  4073.         to = (char *)ip->bw_conv_buf;
  4074.  
  4075.         if (ip->bw_first)
  4076.         {
  4077.         size_t    save_len = tolen;
  4078.  
  4079.         /* output the initial shift state sequence */
  4080.         (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
  4081.  
  4082.         /* There is a bug in iconv() on Linux (which appears to be
  4083.          * wide-spread) which sets "to" to NULL and messes up "tolen".
  4084.          */
  4085.         if (to == NULL)
  4086.         {
  4087.             to = (char *)ip->bw_conv_buf;
  4088.             tolen = save_len;
  4089.         }
  4090.         ip->bw_first = FALSE;
  4091.         }
  4092.  
  4093.         /*
  4094.          * If iconv() has an error or there is not enough room, fail.
  4095.          */
  4096.         if ((iconv(ip->bw_iconv_fd, &from, &fromlen, &to, &tolen)
  4097.             == (size_t)-1 && ICONV_ERRNO != EINVAL)
  4098.                             || fromlen > CONV_RESTLEN)
  4099.         {
  4100.         ip->bw_conv_error = TRUE;
  4101.         return FAIL;
  4102.         }
  4103.  
  4104.         /* copy remainder to ip->bw_rest[] to be used for the next call. */
  4105.         if (fromlen > 0)
  4106.         mch_memmove(ip->bw_rest, (void *)from, fromlen);
  4107.         ip->bw_restlen = (int)fromlen;
  4108.  
  4109.         buf = ip->bw_conv_buf;
  4110.         len = (int)((char_u *)to - ip->bw_conv_buf);
  4111.     }
  4112. # endif
  4113.     }
  4114. #endif /* FEAT_MBYTE */
  4115.  
  4116. #ifdef FEAT_CRYPT
  4117.     if (flags & FIO_ENCRYPTED)        /* encrypt the data */
  4118.     {
  4119.     int ztemp, t, i;
  4120.  
  4121.     for (i = 0; i < len; i++)
  4122.     {
  4123.         ztemp  = buf[i];
  4124.         buf[i] = ZENCODE(ztemp, t);
  4125.     }
  4126.     }
  4127. #endif
  4128.  
  4129.     /* Repeat the write(), it may be interrupted by a signal. */
  4130.     while (len)
  4131.     {
  4132.     wlen = vim_write(ip->bw_fd, buf, len);
  4133.     if (wlen <= 0)            /* error! */
  4134.         return FAIL;
  4135.     len -= wlen;
  4136.     buf += wlen;
  4137.     }
  4138.     return OK;
  4139. }
  4140.  
  4141. #ifdef FEAT_MBYTE
  4142. /*
  4143.  * Convert a Unicode character to bytes.
  4144.  */
  4145.     static int
  4146. ucs2bytes(c, pp, flags)
  4147.     unsigned    c;        /* in: character */
  4148.     char_u    **pp;        /* in/out: pointer to result */
  4149.     int        flags;        /* FIO_ flags */
  4150. {
  4151.     char_u    *p = *pp;
  4152.     int        error = FALSE;
  4153.     int        cc;
  4154.  
  4155.  
  4156.     if (flags & FIO_UCS4)
  4157.     {
  4158.     if (flags & FIO_ENDIAN_L)
  4159.     {
  4160.         *p++ = c;
  4161.         *p++ = (c >> 8);
  4162.         *p++ = (c >> 16);
  4163.         *p++ = (c >> 24);
  4164.     }
  4165.     else
  4166.     {
  4167.         *p++ = (c >> 24);
  4168.         *p++ = (c >> 16);
  4169.         *p++ = (c >> 8);
  4170.         *p++ = c;
  4171.     }
  4172.     }
  4173.     else if (flags & (FIO_UCS2 | FIO_UTF16))
  4174.     {
  4175.     if (c >= 0x10000)
  4176.     {
  4177.         if (flags & FIO_UTF16)
  4178.         {
  4179.         /* Make two words, ten bits of the character in each.  First
  4180.          * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
  4181.         c -= 0x10000;
  4182.         if (c >= 0x100000)
  4183.             error = TRUE;
  4184.         cc = ((c >> 10) & 0x3ff) + 0xd800;
  4185.         if (flags & FIO_ENDIAN_L)
  4186.         {
  4187.             *p++ = cc;
  4188.             *p++ = ((unsigned)cc >> 8);
  4189.         }
  4190.         else
  4191.         {
  4192.             *p++ = ((unsigned)cc >> 8);
  4193.             *p++ = cc;
  4194.         }
  4195.         c = (c & 0x3ff) + 0xdc00;
  4196.         }
  4197.         else
  4198.         error = TRUE;
  4199.     }
  4200.     if (flags & FIO_ENDIAN_L)
  4201.     {
  4202.         *p++ = c;
  4203.         *p++ = (c >> 8);
  4204.     }
  4205.     else
  4206.     {
  4207.         *p++ = (c >> 8);
  4208.         *p++ = c;
  4209.     }
  4210.     }
  4211.     else    /* Latin1 */
  4212.     {
  4213.     if (c >= 0x100)
  4214.     {
  4215.         error = TRUE;
  4216.         *p++ = 0xBF;
  4217.     }
  4218.     else
  4219.         *p++ = c;
  4220.     }
  4221.  
  4222.     *pp = p;
  4223.     return error;
  4224. }
  4225.  
  4226. /*
  4227.  * Return TRUE if "a" and "b" are the same 'encoding'.
  4228.  * Ignores difference between "ansi" and "latin1", "ucs-4" and "ucs-4be", etc.
  4229.  */
  4230.     static int
  4231. same_encoding(a, b)
  4232.     char_u    *a;
  4233.     char_u    *b;
  4234. {
  4235.     int        f;
  4236.  
  4237.     if (STRCMP(a, b) == 0)
  4238.     return TRUE;
  4239.     f = get_fio_flags(a);
  4240.     return (f != 0 && get_fio_flags(b) == f);
  4241. }
  4242.  
  4243. /*
  4244.  * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
  4245.  * internal conversion.
  4246.  * if "ptr" is an empty string, use 'encoding'.
  4247.  */
  4248.     static int
  4249. get_fio_flags(ptr)
  4250.     char_u    *ptr;
  4251. {
  4252.     int        prop;
  4253.  
  4254.     if (*ptr == NUL)
  4255.     ptr = p_enc;
  4256.  
  4257.     prop = enc_canon_props(ptr);
  4258.     if (prop & ENC_UNICODE)
  4259.     {
  4260.     if (prop & ENC_2BYTE)
  4261.     {
  4262.         if (prop & ENC_ENDIAN_L)
  4263.         return FIO_UCS2 | FIO_ENDIAN_L;
  4264.         return FIO_UCS2;
  4265.     }
  4266.     if (prop & ENC_4BYTE)
  4267.     {
  4268.         if (prop & ENC_ENDIAN_L)
  4269.         return FIO_UCS4 | FIO_ENDIAN_L;
  4270.         return FIO_UCS4;
  4271.     }
  4272.     if (prop & ENC_2WORD)
  4273.     {
  4274.         if (prop & ENC_ENDIAN_L)
  4275.         return FIO_UTF16 | FIO_ENDIAN_L;
  4276.         return FIO_UTF16;
  4277.     }
  4278.     return FIO_UTF8;
  4279.     }
  4280.     if (prop & ENC_LATIN1)
  4281.     return FIO_LATIN1;
  4282.     /* must be ENC_DBCS, requires iconv() */
  4283.     return 0;
  4284. }
  4285.  
  4286. /*
  4287.  * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
  4288.  * "size" must be at least 2.
  4289.  * Return the name of the encoding and set "*lenp" to the length.
  4290.  * Returns NULL when no BOM found.
  4291.  */
  4292.     static char_u *
  4293. check_for_bom(p, size, lenp, flags)
  4294.     char_u    *p;
  4295.     long    size;
  4296.     int        *lenp;
  4297.     int        flags;
  4298. {
  4299.     char    *name = NULL;
  4300.     int        len = 2;
  4301.  
  4302.     if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
  4303.         && (flags == FIO_ALL || flags == 0))
  4304.     {
  4305.     name = "utf-8";        /* EF BB BF */
  4306.     len = 3;
  4307.     }
  4308.     else if (p[0] == 0xff && p[1] == 0xfe)
  4309.     {
  4310.     if (size >= 4 && p[2] == 0 && p[3] == 0
  4311.         && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
  4312.     {
  4313.         name = "ucs-4le";    /* FF FE 00 00 */
  4314.         len = 4;
  4315.     }
  4316.     else if (flags == FIO_ALL || flags == (FIO_UCS2 | FIO_ENDIAN_L))
  4317.         name = "ucs-2le";    /* FF FE */
  4318.     else if (flags == (FIO_UTF16 | FIO_ENDIAN_L))
  4319.         name = "utf-16le";    /* FF FE */
  4320.     }
  4321.     else if (p[0] == 0xfe && p[1] == 0xff
  4322.         && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
  4323.     {
  4324.     if (flags == FIO_UTF16)
  4325.         name = "utf-16";    /* FE FF */
  4326.     else
  4327.         name = "ucs-2";    /* FE FF */
  4328.     }
  4329.     else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
  4330.         && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
  4331.     {
  4332.     name = "ucs-4";        /* 00 00 FE FF */
  4333.     len = 4;
  4334.     }
  4335.  
  4336.     *lenp = len;
  4337.     return (char_u *)name;
  4338. }
  4339.  
  4340. /*
  4341.  * Generate a BOM in "buf[4]" for encoding "name".
  4342.  * Return the length of the BOM (zero when no BOM).
  4343.  */
  4344.     static int
  4345. make_bom(buf, name)
  4346.     char_u    *buf;
  4347.     char_u    *name;
  4348. {
  4349.     int        flags;
  4350.     char_u    *p;
  4351.  
  4352.     flags = get_fio_flags(name);
  4353.  
  4354.     /* Can't put a BOM in a non-Unicode file. */
  4355.     if (flags == FIO_LATIN1 || flags == 0)
  4356.     return 0;
  4357.  
  4358.     if (flags == FIO_UTF8)    /* UTF-8 */
  4359.     {
  4360.     buf[0] = 0xef;
  4361.     buf[1] = 0xbb;
  4362.     buf[2] = 0xbf;
  4363.     return 3;
  4364.     }
  4365.     p = buf;
  4366.     (void)ucs2bytes(0xfeff, &p, flags);
  4367.     return (int)(p - buf);
  4368. }
  4369. #endif
  4370.  
  4371. /*
  4372.  * Try to find a shortname by comparing the fullname with the current
  4373.  * directory.
  4374.  * Returns NULL if not shorter name possible, pointer into "full_path"
  4375.  * otherwise.
  4376.  */
  4377.     char_u *
  4378. shorten_fname(full_path, dir_name)
  4379.     char_u    *full_path;
  4380.     char_u    *dir_name;
  4381. {
  4382.     int            len;
  4383.     char_u        *p;
  4384.  
  4385.     if (full_path == NULL)
  4386.     return NULL;
  4387.     len = (int)STRLEN(dir_name);
  4388.     if (fnamencmp(dir_name, full_path, len) == 0)
  4389.     {
  4390.     p = full_path + len;
  4391. #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
  4392.     /*
  4393.      * MSDOS: when a file is in the root directory, dir_name will end in a
  4394.      * slash, since C: by itself does not define a specific dir. In this
  4395.      * case p may already be correct. <negri>
  4396.      */
  4397.     if (!((len > 2) && (*(p - 2) == ':')))
  4398. #endif
  4399.     {
  4400.         if (vim_ispathsep(*p))
  4401.         ++p;
  4402. #ifndef VMS   /* the path separator is always part of the path */
  4403.         else
  4404.         p = NULL;
  4405. #endif
  4406.     }
  4407.     }
  4408. #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
  4409.     /*
  4410.      * When using a file in the current drive, remove the drive name:
  4411.      * "A:\dir\file" -> "\dir\file".  This helps when moving a session file on
  4412.      * a floppy from "A:\dir" to "B:\dir".
  4413.      */
  4414.     else if (len > 3
  4415.         && TO_UPPER(full_path[0]) == TO_UPPER(dir_name[0])
  4416.         && full_path[1] == ':'
  4417.         && vim_ispathsep(full_path[2]))
  4418.     p = full_path + 2;
  4419. #endif
  4420.     else
  4421.     p = NULL;
  4422.     return p;
  4423. }
  4424.  
  4425. /*
  4426.  * When "force" is TRUE: Use full path from now on for files currently being
  4427.  * edited, both for file name and swap file name.  Try to shorten the file
  4428.  * names a bit, if safe to do so.
  4429.  * When "force" is FALSE: Only try to shorten absolute file names.
  4430.  * For buffers that have buftype "nofile" or "scratch": never change the file
  4431.  * name.
  4432.  */
  4433.     void
  4434. shorten_fnames(force)
  4435.     int        force;
  4436. {
  4437.     char_u    dirname[MAXPATHL];
  4438.     buf_T    *buf;
  4439.     char_u    *p;
  4440.  
  4441.     mch_dirname(dirname, MAXPATHL);
  4442.     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  4443.     {
  4444.     if (buf->b_fname != NULL
  4445. #ifdef FEAT_QUICKFIX
  4446.         && !bt_nofile(buf)
  4447. #endif
  4448.         && !path_with_url(buf->b_fname)
  4449.         && (force
  4450.             || buf->b_sfname == NULL
  4451.             || mch_isFullName(buf->b_sfname)))
  4452.     {
  4453.         vim_free(buf->b_sfname);
  4454.         buf->b_sfname = NULL;
  4455.         p = shorten_fname(buf->b_ffname, dirname);
  4456.         if (p != NULL)
  4457.         {
  4458.         buf->b_sfname = vim_strsave(p);
  4459.         buf->b_fname = buf->b_sfname;
  4460.         }
  4461.         if (p == NULL || buf->b_fname == NULL)
  4462.         buf->b_fname = buf->b_ffname;
  4463.         mf_fullname(buf->b_ml.ml_mfp);
  4464.     }
  4465.     }
  4466. #ifdef FEAT_WINDOWS
  4467.     status_redraw_all();
  4468. #endif
  4469. }
  4470.  
  4471. /*
  4472.  * add extention to file name - change path/fo.o.h to path/fo.o.h.ext or
  4473.  * fo_o_h.ext for MSDOS or when shortname option set.
  4474.  *
  4475.  * Assumed that fname is a valid name found in the filesystem we assure that
  4476.  * the return value is a different name and ends in 'ext'.
  4477.  * "ext" MUST be at most 4 characters long if it starts with a dot, 3
  4478.  * characters otherwise.
  4479.  * Space for the returned name is allocated, must be freed later.
  4480.  * Returns NULL when out of memory.
  4481.  */
  4482.     char_u *
  4483. modname(fname, ext, prepend_dot)
  4484.     char_u *fname, *ext;
  4485.     int        prepend_dot;    /* may prepend a '.' to file name */
  4486. {
  4487.     return buf_modname(
  4488. #ifdef SHORT_FNAME
  4489.             TRUE,
  4490. #else
  4491.             (curbuf->b_p_sn || curbuf->b_shortname),
  4492. #endif
  4493.                              fname, ext, prepend_dot);
  4494. }
  4495.  
  4496.     char_u *
  4497. buf_modname(shortname, fname, ext, prepend_dot)
  4498.     int        shortname;        /* use 8.3 file name */
  4499.     char_u  *fname, *ext;
  4500.     int        prepend_dot;    /* may prepend a '.' to file name */
  4501. {
  4502.     char_u    *retval;
  4503.     char_u    *s;
  4504.     char_u    *e;
  4505.     char_u    *ptr;
  4506.     int        fnamelen, extlen;
  4507.  
  4508.     extlen = (int)STRLEN(ext);
  4509.  
  4510.     /*
  4511.      * If there is no file name we must get the name of the current directory
  4512.      * (we need the full path in case :cd is used).
  4513.      */
  4514.     if (fname == NULL || *fname == NUL)
  4515.     {
  4516.     retval = alloc((unsigned)(MAXPATHL + extlen + 3));
  4517.     if (retval == NULL)
  4518.         return NULL;
  4519.     if (mch_dirname(retval, MAXPATHL) == FAIL ||
  4520.                      (fnamelen = (int)STRLEN(retval)) == 0)
  4521.     {
  4522.         vim_free(retval);
  4523.         return NULL;
  4524.     }
  4525.     if (!vim_ispathsep(retval[fnamelen - 1]))
  4526.     {
  4527.         retval[fnamelen++] = PATHSEP;
  4528.         retval[fnamelen] = NUL;
  4529.     }
  4530. #ifndef SHORT_FNAME
  4531.     prepend_dot = FALSE;        /* nothing to prepend a dot to */
  4532. #endif
  4533.     }
  4534.     else
  4535.     {
  4536.     fnamelen = (int)STRLEN(fname);
  4537.     retval = alloc((unsigned)(fnamelen + extlen + 3));
  4538.     if (retval == NULL)
  4539.         return NULL;
  4540.     STRCPY(retval, fname);
  4541. #ifdef VMS
  4542.     vms_remove_version(retval); /* we do not need versions here */
  4543.     fnamelen = STRLEN(retval);  /* it can be shorter*/
  4544. #endif
  4545.     }
  4546.  
  4547.     /*
  4548.      * search backwards until we hit a '/', '\' or ':' replacing all '.'
  4549.      * by '_' for MSDOS or when shortname option set and ext starts with a dot.
  4550.      * Then truncate what is after the '/', '\' or ':' to 8 characters for
  4551.      * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
  4552.      */
  4553.     for (ptr = retval + fnamelen; ptr >= retval; ptr--)
  4554.     {
  4555. #ifndef RISCOS
  4556.     if (*ext == '.'
  4557. #ifdef USE_LONG_FNAME
  4558.             && (!USE_LONG_FNAME || shortname)
  4559. #else
  4560. # ifndef SHORT_FNAME
  4561.             && shortname
  4562. # endif
  4563. #endif
  4564.                                 )
  4565.         if (*ptr == '.')    /* replace '.' by '_' */
  4566.         *ptr = '_';
  4567. #endif /* RISCOS */
  4568.     if (vim_ispathsep(*ptr))
  4569.         break;
  4570.     }
  4571.     ptr++;
  4572.  
  4573.     /* the file name has at most BASENAMELEN characters. */
  4574. #ifndef SHORT_FNAME
  4575.     if (STRLEN(ptr) > (unsigned)BASENAMELEN)
  4576.     ptr[BASENAMELEN] = '\0';
  4577. #endif
  4578.  
  4579.     s = ptr + STRLEN(ptr);
  4580.  
  4581.     /*
  4582.      * For 8.3 file names we may have to reduce the length.
  4583.      */
  4584. #ifdef USE_LONG_FNAME
  4585.     if (!USE_LONG_FNAME || shortname)
  4586. #else
  4587. # ifndef SHORT_FNAME
  4588.     if (shortname)
  4589. # endif
  4590. #endif
  4591.     {
  4592.     /*
  4593.      * If there is no file name, or the file name ends in '/', and the
  4594.      * extension starts with '.', put a '_' before the dot, because just
  4595.      * ".ext" is invalid.
  4596.      */
  4597.     if (fname == NULL || *fname == NUL
  4598.                    || vim_ispathsep(fname[STRLEN(fname) - 1]))
  4599.     {
  4600. #ifdef RISCOS
  4601.         if (*ext == '/')
  4602. #else
  4603.         if (*ext == '.')
  4604. #endif
  4605.         *s++ = '_';
  4606.     }
  4607.     /*
  4608.      * If the extension starts with '.', truncate the base name at 8
  4609.      * characters
  4610.      */
  4611. #ifdef RISCOS
  4612.     /* We normally use '/', but swap files are '_' */
  4613.     else if (*ext == '/' || *ext == '_')
  4614. #else
  4615.     else if (*ext == '.')
  4616. #endif
  4617.     {
  4618.         if (s - ptr > (size_t)8)
  4619.         {
  4620.         s = ptr + 8;
  4621.         *s = '\0';
  4622.         }
  4623.     }
  4624.     /*
  4625.      * If the extension doesn't start with '.', and the file name
  4626.      * doesn't have an extension yet, append a '.'
  4627.      */
  4628. #ifdef RISCOS
  4629.     else if ((e = vim_strchr(ptr, '/')) == NULL)
  4630.         *s++ = '/';
  4631. #else
  4632.     else if ((e = vim_strchr(ptr, '.')) == NULL)
  4633.         *s++ = '.';
  4634. #endif
  4635.     /*
  4636.      * If the extension doesn't start with '.', and there already is an
  4637.      * extension, it may need to be tructated
  4638.      */
  4639.     else if ((int)STRLEN(e) + extlen > 4)
  4640.         s = e + 4 - extlen;
  4641.     }
  4642. #if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
  4643.     /*
  4644.      * If there is no file name, and the extension starts with '.', put a
  4645.      * '_' before the dot, because just ".ext" may be invalid if it's on a
  4646.      * FAT partition, and on HPFS it doesn't matter.
  4647.      */
  4648.     else if ((fname == NULL || *fname == NUL) && *ext == '.')
  4649.     *s++ = '_';
  4650. #endif
  4651.  
  4652.     /*
  4653.      * Append the extention.
  4654.      * ext can start with '.' and cannot exceed 3 more characters.
  4655.      */
  4656.     STRCPY(s, ext);
  4657.  
  4658. #ifndef SHORT_FNAME
  4659.     /*
  4660.      * Prepend the dot.
  4661.      */
  4662.     if (prepend_dot && !shortname && *(e = gettail(retval)) !=
  4663. #ifdef RISCOS
  4664.         '/'
  4665. #else
  4666.         '.'
  4667. #endif
  4668. #ifdef USE_LONG_FNAME
  4669.         && USE_LONG_FNAME
  4670. #endif
  4671.                 )
  4672.     {
  4673.     mch_memmove(e + 1, e, STRLEN(e) + 1);
  4674. #ifdef RISCOS
  4675.     *e = '/';
  4676. #else
  4677.     *e = '.';
  4678. #endif
  4679.     }
  4680. #endif
  4681.  
  4682.     /*
  4683.      * Check that, after appending the extension, the file name is really
  4684.      * different.
  4685.      */
  4686.     if (fname != NULL && STRCMP(fname, retval) == 0)
  4687.     {
  4688.     /* we search for a character that can be replaced by '_' */
  4689.     while (--s >= ptr)
  4690.     {
  4691.         if (*s != '_')
  4692.         {
  4693.         *s = '_';
  4694.         break;
  4695.         }
  4696.     }
  4697.     if (s < ptr)    /* fname was "________.<ext>", how tricky! */
  4698.         *ptr = 'v';
  4699.     }
  4700.     return retval;
  4701. }
  4702.  
  4703. /*
  4704.  * Like fgets(), but if the file line is too long, it is truncated and the
  4705.  * rest of the line is thrown away.  Returns TRUE for end-of-file.
  4706.  */
  4707.     int
  4708. vim_fgets(buf, size, fp)
  4709.     char_u    *buf;
  4710.     int        size;
  4711.     FILE    *fp;
  4712. {
  4713.     char    *eof;
  4714. #define FGETS_SIZE 200
  4715.     char    tbuf[FGETS_SIZE];
  4716.  
  4717.     buf[size - 2] = NUL;
  4718. #ifdef USE_CR
  4719.     eof = fgets_cr((char *)buf, size, fp);
  4720. #else
  4721.     eof = fgets((char *)buf, size, fp);
  4722. #endif
  4723.     if (buf[size - 2] != NUL && buf[size - 2] != '\n')
  4724.     {
  4725.     buf[size - 1] = NUL;        /* Truncate the line */
  4726.  
  4727.     /* Now throw away the rest of the line: */
  4728.     do
  4729.     {
  4730.         tbuf[FGETS_SIZE - 2] = NUL;
  4731. #ifdef USE_CR
  4732.         fgets_cr((char *)tbuf, FGETS_SIZE, fp);
  4733. #else
  4734.         fgets((char *)tbuf, FGETS_SIZE, fp);
  4735. #endif
  4736.     } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
  4737.     }
  4738.     return (eof == NULL);
  4739. }
  4740.  
  4741. #if defined(USE_CR) || defined(PROTO)
  4742. /*
  4743.  * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
  4744.  * Returns TRUE for end-of-file.
  4745.  * Only used for the Mac, because it's much slower than vim_fgets().
  4746.  */
  4747.     int
  4748. tag_fgets(buf, size, fp)
  4749.     char_u    *buf;
  4750.     int        size;
  4751.     FILE    *fp;
  4752. {
  4753.     int        i = 0;
  4754.     int        c;
  4755.     int        eof = FALSE;
  4756.  
  4757.     for (;;)
  4758.     {
  4759.     c = fgetc(fp);
  4760.     if (c == EOF)
  4761.     {
  4762.         eof = TRUE;
  4763.         break;
  4764.     }
  4765.     if (c == '\r')
  4766.     {
  4767.         /* Always store a NL for end-of-line. */
  4768.         if (i < size - 1)
  4769.         buf[i++] = '\n';
  4770.         c = fgetc(fp);
  4771.         if (c != '\n')    /* Macintosh format: single CR. */
  4772.         ungetc(c, fp);
  4773.         break;
  4774.     }
  4775.     if (i < size - 1)
  4776.         buf[i++] = c;
  4777.     if (c == '\n')
  4778.         break;
  4779.     }
  4780.     buf[i] = NUL;
  4781.     return eof;
  4782. }
  4783. #endif
  4784.  
  4785. /*
  4786.  * rename() only works if both files are on the same file system, this
  4787.  * function will (attempts to?) copy the file across if rename fails -- webb
  4788.  * Return -1 for failure, 0 for success.
  4789.  */
  4790.     int
  4791. vim_rename(from, to)
  4792.     char_u    *from;
  4793.     char_u    *to;
  4794. {
  4795.     int        fd_in;
  4796.     int        fd_out;
  4797.     int        n;
  4798.     char    *errmsg = NULL;
  4799.     char    *buffer;
  4800. #ifdef AMIGA
  4801.     BPTR    flock;
  4802. #endif
  4803.  
  4804.     /*
  4805.      * First delete the "to" file, this is required on some systems to make
  4806.      * the mch_rename() work, on other systems it makes sure that we don't
  4807.      * have two files when the mch_rename() fails.
  4808.      */
  4809.  
  4810. #ifdef AMIGA
  4811.     /*
  4812.      * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
  4813.      * that the name of the "to" file is the same as the "from" file. To
  4814.      * avoid the chance of accidently deleting the "from" file (horror!) we
  4815.      * lock it during the remove.
  4816.      * When used for making a backup before writing the file: This should not
  4817.      * happen with ":w", because startscript() should detect this problem and
  4818.      * set buf->b_shortname, causing modname() to return a correct ".bak" file
  4819.      * name.  This problem does exist with ":w filename", but then the
  4820.      * original file will be somewhere else so the backup isn't really
  4821.      * important. If autoscripting is off the rename may fail.
  4822.      */
  4823.     flock = Lock((UBYTE *)from, (long)ACCESS_READ);
  4824. #endif
  4825.     mch_remove(to);
  4826. #ifdef AMIGA
  4827.     if (flock)
  4828.     UnLock(flock);
  4829. #endif
  4830.  
  4831.     /*
  4832.      * First try a normal rename, return if it works.
  4833.      */
  4834.     if (mch_rename((char *)from, (char *)to) == 0)
  4835.     return 0;
  4836.  
  4837.     /*
  4838.      * Rename() failed, try copying the file.
  4839.      */
  4840.     fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
  4841.     if (fd_in == -1)
  4842.     return -1;
  4843.     fd_out = mch_open((char *)to, O_CREAT|O_EXCL|O_WRONLY|O_EXTRA, 0666);
  4844.     if (fd_out == -1)
  4845.     {
  4846.     close(fd_in);
  4847.     return -1;
  4848.     }
  4849.  
  4850.     buffer = (char *)alloc(BUFSIZE);
  4851.     if (buffer == NULL)
  4852.     {
  4853.     close(fd_in);
  4854.     close(fd_out);
  4855.     return -1;
  4856.     }
  4857.  
  4858.     while ((n = vim_read(fd_in, buffer, BUFSIZE)) > 0)
  4859.     if (vim_write(fd_out, buffer, n) != n)
  4860.     {
  4861.         errmsg = _("E208: Error writing to \"%s\"");
  4862.         break;
  4863.     }
  4864.  
  4865.     vim_free(buffer);
  4866.     close(fd_in);
  4867.     if (close(fd_out) < 0)
  4868.     errmsg = _("E209: Error closing \"%s\"");
  4869.     if (n < 0)
  4870.     {
  4871.     errmsg = _("E210: Error reading \"%s\"");
  4872.     to = from;
  4873.     }
  4874.     if (errmsg != NULL)
  4875.     {
  4876.     EMSG2(errmsg, to);
  4877.     return -1;
  4878.     }
  4879.     mch_remove(from);
  4880.     return 0;
  4881. }
  4882.  
  4883. static int already_warned = FALSE;
  4884.  
  4885. /*
  4886.  * Check if any not hidden buffer has been changed.
  4887.  * Postpone the check if there are characters in the stuff buffer, a global
  4888.  * command is being executed, a mapping is being executed or an autocommand is
  4889.  * busy.
  4890.  * Returns TRUE if some message was written (screen should be redrawn and
  4891.  * cursor positioned).
  4892.  */
  4893.     int
  4894. check_timestamps(focus)
  4895.     int        focus;        /* called for GUI focus event */
  4896. {
  4897.     buf_T    *buf;
  4898.     int        didit = 0;
  4899.     int        n;
  4900.  
  4901.     /* Avoid doing a check twice.  The OK/Reload dialog can cause a focus
  4902.      * event and we would keep on checking if the file is steadily growing.
  4903.      * Do check again after typing something. */
  4904.     if (focus && did_check_timestamps)
  4905.     {
  4906.     need_check_timestamps = TRUE;
  4907.     return FALSE;
  4908.     }
  4909.  
  4910.     if (!stuff_empty() || global_busy || !typebuf_typed()
  4911. #ifdef FEAT_AUTOCMD
  4912.             || autocmd_busy
  4913. #endif
  4914.                     )
  4915.     need_check_timestamps = TRUE;        /* check later */
  4916.     else
  4917.     {
  4918.     ++no_wait_return;
  4919.     did_check_timestamps = TRUE;
  4920.     already_warned = FALSE;
  4921.     for (buf = firstbuf; buf != NULL; )
  4922.     {
  4923.         /* Only check buffers in a window. */
  4924.         if (buf->b_nwindows > 0)
  4925.         {
  4926.         n = buf_check_timestamp(buf, focus);
  4927.         if (didit < n)
  4928.             didit = n;
  4929.         if (n > 0 && !buf_valid(buf))
  4930.         {
  4931.             /* Autocommands have removed the buffer, start at the
  4932.              * first one again. */
  4933.             buf = firstbuf;
  4934.             continue;
  4935.         }
  4936.         }
  4937.         buf = buf->b_next;
  4938.     }
  4939.     --no_wait_return;
  4940.     need_check_timestamps = FALSE;
  4941.     if (need_wait_return && didit == 2)
  4942.     {
  4943.         /* make sure msg isn't overwritten */
  4944.         msg_puts((char_u *)"\n");
  4945.         out_flush();
  4946.     }
  4947.     }
  4948.     return didit;
  4949. }
  4950.  
  4951. /*
  4952.  * Check if buffer "buf" has been changed.
  4953.  * Also check if the file for a new buffer unexpectedly appeared.
  4954.  * return 1 if a changed buffer was found.
  4955.  * return 2 if a message has been displayed.
  4956.  * return 0 otherwise.
  4957.  */
  4958. /*ARGSUSED*/
  4959.     int
  4960. buf_check_timestamp(buf, focus)
  4961.     buf_T    *buf;
  4962.     int        focus;        /* called for GUI focus event */
  4963. {
  4964.     struct stat    st;
  4965.     int        stat_res;
  4966.     int        retval = 0;
  4967.     char_u    *path;
  4968.     char_u    *tbuf;
  4969.     char    *mesg = NULL;
  4970.     int        reload = FALSE;
  4971. #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
  4972.     int        can_reload = FALSE;
  4973. #endif
  4974.     size_t    orig_size = buf->b_orig_size;
  4975.     int        orig_mode = buf->b_orig_mode;
  4976.  
  4977.     /* If there is no file name, the buffer is not loaded, or 'buftype' is
  4978.      * set: ignore this buffer. */
  4979.     if (buf->b_ffname == NULL
  4980.         || buf->b_ml.ml_mfp == NULL
  4981. #if defined(FEAT_QUICKFIX)
  4982.         || *buf->b_p_bt != NUL
  4983. #endif
  4984.         )
  4985.     return 0;
  4986.  
  4987.     if (       !(buf->b_flags & BF_NOTEDITED)
  4988.         && buf->b_mtime != 0
  4989.         && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
  4990.         || time_differs((long)st.st_mtime, buf->b_mtime)
  4991. #ifdef HAVE_ST_MODE
  4992.         || (int)st.st_mode != buf->b_orig_mode
  4993. #else
  4994.         || mch_getperm(buf->b_ffname) != buf->b_orig_mode
  4995. #endif
  4996.         ))
  4997.     {
  4998.     retval = 1;
  4999.  
  5000.     /* set b_mtime to stop further warnings */
  5001.     if (stat_res < 0)
  5002.     {
  5003.         buf->b_mtime = 0;
  5004.         buf->b_orig_size = 0;
  5005.         buf->b_orig_mode = 0;
  5006.     }
  5007.     else
  5008.         buf_store_time(buf, &st, buf->b_ffname);
  5009.  
  5010.     /* Don't do anything for a directory.  Might contain the file
  5011.      * explorer. */
  5012.     if (mch_isdir(buf->b_fname))
  5013.         ;
  5014.  
  5015.     /*
  5016.      * If 'autoread' is set, the buffer has no changes and the file still
  5017.      * exists, reload the buffer.  Use the buffer-local option value if it
  5018.      * was set, the global option value otherwise.
  5019.      */
  5020.     else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
  5021.                        && !bufIsChanged(buf) && stat_res >= 0)
  5022.         reload = TRUE;
  5023.     else
  5024.     {
  5025. #ifdef FEAT_AUTOCMD
  5026.         /*
  5027.          * Only give the warning if there are no FileChangedShell
  5028.          * autocommands.
  5029.          */
  5030.         if (apply_autocmds(EVENT_FILECHANGEDSHELL,
  5031.                       buf->b_fname, buf->b_fname, FALSE, buf))
  5032.         {
  5033.         if (!buf_valid(buf))
  5034.         {
  5035.             EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
  5036.         }
  5037.         return 2;
  5038.         }
  5039.         else
  5040. #endif
  5041.         {
  5042.         if (stat_res < 0)
  5043.             mesg = _("E211: Warning: File \"%s\" no longer available");
  5044.         else
  5045.         {
  5046. #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
  5047.             can_reload = TRUE;
  5048. #endif
  5049.             /*
  5050.              * Check if the file contents really changed to avoid
  5051.              * giving a warning when only the timestamp was set (e.g.,
  5052.              * checked out of CVS).  Always warn when the buffer was
  5053.              * changed.
  5054.              */
  5055.             if (bufIsChanged(buf))
  5056.             mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
  5057.             else if (orig_size != buf->b_orig_size
  5058.                 || buf_contents_changed(buf))
  5059.             mesg = _("W11: Warning: File \"%s\" has changed since editing started");
  5060.             else if (orig_mode != buf->b_orig_mode)
  5061.             mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
  5062.         }
  5063.         }
  5064.     }
  5065.  
  5066.     }
  5067.     else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
  5068.                         && vim_fexists(buf->b_ffname))
  5069.     {
  5070.     retval = 1;
  5071.     mesg = _("W13: Warning: File \"%s\" has been created after editing started");
  5072.     buf->b_flags |= BF_NEW_W;
  5073. #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
  5074.     can_reload = TRUE;
  5075. #endif
  5076.     }
  5077.  
  5078.     if (mesg != NULL)
  5079.     {
  5080.     path = home_replace_save(buf, buf->b_fname);
  5081.     if (path != NULL)
  5082.     {
  5083.         tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)));
  5084.         sprintf((char *)tbuf, mesg, path);
  5085. #if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
  5086.         if (can_reload)
  5087.         {
  5088.         if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
  5089.                 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
  5090.             reload = TRUE;
  5091.         }
  5092.         else
  5093. #endif
  5094.         if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
  5095.         {
  5096.         EMSG(tbuf);
  5097.         retval = 2;
  5098.         }
  5099.         else
  5100.         {
  5101. # ifdef VIMBUDDY
  5102.         VimBuddyText(tbuf + 9, 2);
  5103. # else
  5104. #  ifdef FEAT_AUTOCMD
  5105.         if (!autocmd_busy)
  5106. #  endif
  5107.         {
  5108.             msg_start();
  5109.             msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
  5110.             msg_clr_eos();
  5111.             (void)msg_end();
  5112.             if (emsg_silent == 0)
  5113.             {
  5114.             out_flush();
  5115. #  ifdef FEAT_GUI
  5116.             if (!focus)
  5117. #  endif
  5118.                 /* give the user some time to think about it */
  5119.                 ui_delay(1000L, TRUE);
  5120.  
  5121.             /* don't redraw and erase the message */
  5122.             redraw_cmdline = FALSE;
  5123.             }
  5124.         }
  5125.         already_warned = TRUE;
  5126. # endif
  5127.         }
  5128.  
  5129.         vim_free(path);
  5130.         vim_free(tbuf);
  5131.     }
  5132.     }
  5133.  
  5134.     if (reload)
  5135.     {
  5136.     linenr_T    old_line_count = buf->b_ml.ml_line_count;
  5137.     exarg_T        ea;
  5138.     pos_T        old_cursor;
  5139. #ifdef FEAT_AUTOCMD
  5140.     aco_save_T    aco;
  5141.  
  5142.     /* set curwin/curbuf for "buf" and save some things */
  5143.     aucmd_prepbuf(&aco, buf);
  5144. #else
  5145.     buf_T    *save_curbuf = curbuf;
  5146.  
  5147.     curbuf = buf;
  5148.     curwin->w_buffer = buf;
  5149. #endif
  5150.  
  5151.     /* We only want to read the text from the file, not reset the syntax
  5152.      * highlighting, clear marks, diff status, etc.  Force the fileformat
  5153.      * and encoding to be the same. */
  5154.     if (prep_exarg(&ea, buf) == OK)
  5155.     {
  5156.         old_cursor = curwin->w_cursor;
  5157.         if (bufempty())
  5158.         old_line_count = 0;
  5159.         curbuf->b_flags |= BF_CHECK_RO;    /* check for RO again */
  5160. #ifdef FEAT_AUTOCMD
  5161.         keep_filetype = TRUE;        /* don't detect 'filetype' */
  5162. #endif
  5163.         if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0, (linenr_T)0,
  5164.             (linenr_T)MAXLNUM, &ea, READ_NEW) == FAIL)
  5165.         EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
  5166.         else
  5167.         {
  5168.         /* Delete the old lines. */
  5169.         while (old_line_count-- > 0)
  5170.             ml_delete(buf->b_ml.ml_line_count, FALSE);
  5171.         /* Mark the buffer as unmodified and free undo info. */
  5172.         unchanged(buf, TRUE);
  5173.         u_blockfree(buf);
  5174.         u_clearall(buf);
  5175.         }
  5176.         vim_free(ea.cmd);
  5177.  
  5178.         /* Restore the cursor position and check it (lines may have been
  5179.          * removed). */
  5180.         curwin->w_cursor = old_cursor;
  5181.         check_cursor();
  5182. #ifdef FEAT_AUTOCMD
  5183.         keep_filetype = FALSE;
  5184. #endif
  5185.     }
  5186.  
  5187. #ifdef FEAT_AUTOCMD
  5188.     /* restore curwin/curbuf and a few other things */
  5189.     aucmd_restbuf(&aco);
  5190.  
  5191.     /* Careful: autocommands may have made "buf" invalid! */
  5192. #else
  5193.     curwin->w_buffer = save_curbuf;
  5194.     curbuf = save_curbuf;
  5195. #endif
  5196.     }
  5197.  
  5198.     return retval;
  5199. }
  5200.  
  5201. /*ARGSUSED*/
  5202.     void
  5203. buf_store_time(buf, st, fname)
  5204.     buf_T    *buf;
  5205.     struct stat    *st;
  5206.     char_u    *fname;
  5207. {
  5208.     buf->b_mtime = (long)st->st_mtime;
  5209.     buf->b_orig_size = (size_t)st->st_size;
  5210. #ifdef HAVE_ST_MODE
  5211.     buf->b_orig_mode = (int)st->st_mode;
  5212. #else
  5213.     buf->b_orig_mode = mch_getperm(fname);
  5214. #endif
  5215. }
  5216.  
  5217. /*
  5218.  * Adjust the line with missing eol, used for the next write.
  5219.  * Used for do_filter(), when the input lines for the filter are deleted.
  5220.  */
  5221.     void
  5222. write_lnum_adjust(offset)
  5223.     linenr_T    offset;
  5224. {
  5225.     if (write_no_eol_lnum)        /* only if there is a missing eol */
  5226.     write_no_eol_lnum += offset;
  5227. }
  5228.  
  5229. #if defined(TEMPDIRNAMES) || defined(PROTO)
  5230. static long    temp_count = 0;        /* Temp filename counter. */
  5231.  
  5232. /*
  5233.  * Delete the temp directory and all files it contains.
  5234.  */
  5235.     void
  5236. vim_deltempdir()
  5237. {
  5238.     char_u    **files;
  5239.     int        file_count;
  5240.     int        i;
  5241.  
  5242.     if (vim_tempdir != NULL)
  5243.     {
  5244.     sprintf((char *)NameBuff, "%s*", vim_tempdir);
  5245.     if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
  5246.                           EW_DIR|EW_FILE|EW_SILENT) == OK)
  5247.     {
  5248.         for (i = 0; i < file_count; ++i)
  5249.         mch_remove(files[i]);
  5250.         FreeWild(file_count, files);
  5251.     }
  5252.     gettail(NameBuff)[-1] = NUL;
  5253.     (void)mch_rmdir(NameBuff);
  5254.  
  5255.     vim_free(vim_tempdir);
  5256.     vim_tempdir = NULL;
  5257.     }
  5258. }
  5259. #endif
  5260.  
  5261. /*
  5262.  * vim_tempname(): Return a unique name that can be used for a temp file.
  5263.  *
  5264.  * The temp file is NOT created.
  5265.  *
  5266.  * The returned pointer is to allocated memory.
  5267.  * The returned pointer is NULL if no valid name was found.
  5268.  */
  5269. /*ARGSUSED*/
  5270.     char_u  *
  5271. vim_tempname(extra_char)
  5272.     int        extra_char;        /* character to use in the name instead of '?' */
  5273. {
  5274. #ifdef USE_TMPNAM
  5275.     char_u    itmp[L_tmpnam];    /* use tmpnam() */
  5276. #else
  5277.     char_u    itmp[TEMPNAMELEN];
  5278. #endif
  5279.  
  5280. #ifdef TEMPDIRNAMES
  5281.     static char    *(tempdirs[]) = {TEMPDIRNAMES};
  5282.     int        i;
  5283.     long    nr;
  5284.     long    off;
  5285. # ifndef EEXIST
  5286.     struct stat    st;
  5287. # endif
  5288.  
  5289.     /*
  5290.      * This will create a directory for private use by this instance of Vim.
  5291.      * This is done once, and the same directory is used for all temp files.
  5292.      * This method avoids security problems because of symlink attacks et al.
  5293.      * It's also a bit faster, because we only need to check for an existing
  5294.      * file when creating the directory and not for each temp file.
  5295.      */
  5296.     if (vim_tempdir == NULL)
  5297.     {
  5298.     /*
  5299.      * Try the entries in TEMPDIRNAMES to create the temp directory.
  5300.      */
  5301.     for (i = 0; i < sizeof(tempdirs) / sizeof(char *); ++i)
  5302.     {
  5303.         /* expand $TMP, leave room for "/v1100000/999999999" */
  5304.         expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
  5305.         if (mch_isdir(itmp))        /* directory exists */
  5306.         {
  5307. # ifdef __EMX__
  5308.         /* If $TMP contains a forward slash (perhaps using bash or
  5309.          * tcsh), don't add a backslash, use a forward slash!
  5310.          * Adding 2 backslashes didn't work. */
  5311.         if (vim_strchr(itmp, '/') != NULL)
  5312.             STRCAT(itmp, "/");
  5313.         else
  5314. # endif
  5315.             add_pathsep(itmp);
  5316.  
  5317.         /* Get an arbitrary number of up to 6 digits.  When it's
  5318.          * unlikely that it already exists it will be faster,
  5319.          * otherwise it doesn't matter.  The use of mkdir() avoids any
  5320.          * security problems because of the predictable number. */
  5321.         nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
  5322.  
  5323.         /* Try up to 10000 different values until we find a name that
  5324.          * doesn't exist. */
  5325.         for (off = 0; off < 10000L; ++off)
  5326.         {
  5327.             int        r;
  5328. #if defined(UNIX) || defined(VMS)
  5329.             mode_t    umask_save;
  5330. #endif
  5331.  
  5332.             sprintf((char *)itmp + STRLEN(itmp), "v%ld", nr + off);
  5333. # ifndef EEXIST
  5334.             /* If mkdir() does not set errno to EEXIST, check for
  5335.              * existing file here.  There is a race condition then,
  5336.              * although it's fail-safe. */
  5337.             if (mch_stat((char *)itmp, &st) >= 0)
  5338.             continue;
  5339. # endif
  5340. #if defined(UNIX) || defined(VMS)
  5341.             /* Make sure the umask doesn't remove the executable bit.
  5342.              * "repl" has been reported to use "177". */
  5343.             umask_save = umask(077);
  5344. #endif
  5345.             r = vim_mkdir(itmp, 0700);
  5346. #if defined(UNIX) || defined(VMS)
  5347.             (void)umask(umask_save);
  5348. #endif
  5349.             if (r == 0)
  5350.             {
  5351.             /* Directory was created, use this name. */
  5352. # ifdef __EMX__
  5353.             if (vim_strchr(itmp, '/') != NULL)
  5354.                 STRCAT(itmp, "/");
  5355.             else
  5356. # endif
  5357.                 add_pathsep(itmp);
  5358.             /* Use the full path; When using the current directory
  5359.              * a ":cd" would confuse us. */
  5360.             vim_tempdir = FullName_save(itmp, FALSE);
  5361.             break;
  5362.             }
  5363. # ifdef EEXIST
  5364.             /* If the mkdir() didn't fail because the file/dir exists,
  5365.              * we probably can't create any dir here, try another
  5366.              * place. */
  5367.             if (errno != EEXIST)
  5368. # endif
  5369.             break;
  5370.         }
  5371.         if (vim_tempdir != NULL)
  5372.             break;
  5373.         }
  5374.     }
  5375.     }
  5376.  
  5377.     if (vim_tempdir != NULL)
  5378.     {
  5379.     /* There is no need to check if the file exists, because we own the
  5380.      * directory and nobody else creates a file in it. */
  5381.     sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
  5382.     return vim_strsave(itmp);
  5383.     }
  5384.  
  5385.     return NULL;
  5386.  
  5387. #else /* TEMPDIRNAMES */
  5388.  
  5389. # ifdef WIN3264
  5390.     char    szTempFile[_MAX_PATH + 1];
  5391.     char    buf4[4];
  5392.     char_u    *retval;
  5393.     char_u    *p;
  5394.  
  5395.     STRCPY(itmp, "");
  5396.     if (GetTempPath(_MAX_PATH, szTempFile) == 0)
  5397.     szTempFile[0] = NUL;    /* GetTempPath() failed, use current dir */
  5398.     strcpy(buf4, "VIM");
  5399.     buf4[2] = extra_char;   /* make it "VIa", "VIb", etc. */
  5400.     if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
  5401.     return NULL;
  5402.     /* GetTempFileName() will create the file, we don't want that */
  5403.     (void)DeleteFile(itmp);
  5404.  
  5405.     /* Backslashes in a temp file name cause problems when filtering with
  5406.      * "sh".  NOTE: This also checks 'shellcmdflag' to help those people who
  5407.      * didn't set 'shellslash'. */
  5408.     retval = vim_strsave(itmp);
  5409.     if (*p_shcf == '-' || p_ssl)
  5410.     for (p = retval; *p; ++p)
  5411.         if (*p == '\\')
  5412.         *p = '/';
  5413.     return retval;
  5414.  
  5415. # else /* WIN3264 */
  5416.  
  5417. #  ifdef USE_TMPNAM
  5418.     /* tmpnam() will make its own name */
  5419.     if (*tmpnam((char *)itmp) == NUL)
  5420.     return NULL;
  5421. #  else
  5422.     char_u    *p;
  5423.  
  5424. #   ifdef VMS_TEMPNAM
  5425.     /* mktemp() is not working on VMS.  It seems to be
  5426.      * a do-nothing function. Therefore we use tempnam().
  5427.      */
  5428.     sprintf((char *)itmp, "VIM%c", extra_char);
  5429.     p = (char_u *)tempnam("tmp:", (char *)itmp);
  5430.     if (p != NULL)
  5431.     {
  5432.     /* VMS will use '.LOG' if we don't explicitly specify an extension,
  5433.      * and VIM will then be unable to find the file later */
  5434.     STRCPY(itmp, p);
  5435.     STRCAT(itmp, ".txt");
  5436.     free(p);
  5437.     }
  5438.     else
  5439.     return NULL;
  5440. #   else
  5441.     STRCPY(itmp, TEMPNAME);
  5442.     if ((p = vim_strchr(itmp, '?')) != NULL)
  5443.     *p = extra_char;
  5444.     if (mktemp((char *)itmp) == NULL)
  5445.     return NULL;
  5446. #   endif
  5447. #  endif
  5448. # endif /* WIN3264 */
  5449.  
  5450.     return vim_strsave(itmp);
  5451. #endif /* TEMPDIRNAMES */
  5452. }
  5453.  
  5454. /*
  5455.  * Code for automatic commands.
  5456.  *
  5457.  * Only included when "FEAT_AUTOCMD" has been defined.
  5458.  */
  5459.  
  5460. #if defined(FEAT_AUTOCMD) || defined(PROTO)
  5461.  
  5462. /*
  5463.  * The autocommands are stored in a list for each event.
  5464.  * Autocommands for the same pattern, that are consecutive, are joined
  5465.  * together, to avoid having to match the pattern too often.
  5466.  * The result is an array of Autopat lists, which point to AutoCmd lists:
  5467.  *
  5468.  * first_autopat[0] --> Autopat.next  -->  Autopat.next -->  NULL
  5469.  *            Autopat.cmds       Autopat.cmds
  5470.  *                |             |
  5471.  *                V             V
  5472.  *            AutoCmd.next       AutoCmd.next
  5473.  *                |             |
  5474.  *                V             V
  5475.  *            AutoCmd.next        NULL
  5476.  *                |
  5477.  *                V
  5478.  *               NULL
  5479.  *
  5480.  * first_autopat[1] --> Autopat.next  -->  NULL
  5481.  *            Autopat.cmds
  5482.  *                |
  5483.  *                V
  5484.  *            AutoCmd.next
  5485.  *                |
  5486.  *                V
  5487.  *               NULL
  5488.  *   etc.
  5489.  *
  5490.  *   The order of AutoCmds is important, this is the order in which they were
  5491.  *   defined and will have to be executed.
  5492.  */
  5493. typedef struct AutoCmd
  5494. {
  5495.     char_u        *cmd;        /* The command to be executed (NULL
  5496.                        when command has been removed) */
  5497.     char        nested;        /* If autocommands nest here */
  5498.     char        last;        /* last command in list */
  5499. #ifdef FEAT_EVAL
  5500.     scid_T        scriptID;        /* script ID where defined */
  5501. #endif
  5502.     struct AutoCmd  *next;        /* Next AutoCmd in list */
  5503. } AutoCmd;
  5504.  
  5505. typedef struct AutoPat
  5506. {
  5507.     int            group;        /* group ID */
  5508.     char_u        *pat;        /* pattern as typed (NULL when pattern
  5509.                        has been removed) */
  5510.     int            patlen;        /* strlen() of pat */
  5511.     char_u        *reg_pat;        /* pattern converted to regexp */
  5512.     char        allow_dirs;        /* Pattern may match whole path */
  5513.     char        last;        /* last pattern for apply_autocmds() */
  5514.     AutoCmd        *cmds;        /* list of commands to do */
  5515.     struct AutoPat  *next;        /* next AutoPat in AutoPat list */
  5516. } AutoPat;
  5517.  
  5518. static struct event_name
  5519. {
  5520.     char    *name;    /* event name */
  5521.     EVENT_T    event;    /* event number */
  5522. } event_names[] =
  5523. {
  5524.     {"BufAdd",        EVENT_BUFADD},
  5525.     {"BufCreate",    EVENT_BUFADD},
  5526.     {"BufDelete",    EVENT_BUFDELETE},
  5527.     {"BufEnter",    EVENT_BUFENTER},
  5528.     {"BufFilePost",    EVENT_BUFFILEPOST},
  5529.     {"BufFilePre",    EVENT_BUFFILEPRE},
  5530.     {"BufHidden",    EVENT_BUFHIDDEN},
  5531.     {"BufLeave",    EVENT_BUFLEAVE},
  5532.     {"BufNew",        EVENT_BUFNEW},
  5533.     {"BufNewFile",    EVENT_BUFNEWFILE},
  5534.     {"BufRead",        EVENT_BUFREADPOST},
  5535.     {"BufReadCmd",    EVENT_BUFREADCMD},
  5536.     {"BufReadPost",    EVENT_BUFREADPOST},
  5537.     {"BufReadPre",    EVENT_BUFREADPRE},
  5538.     {"BufUnload",    EVENT_BUFUNLOAD},
  5539.     {"BufWinEnter",    EVENT_BUFWINENTER},
  5540.     {"BufWinLeave",    EVENT_BUFWINLEAVE},
  5541.     {"BufWipeout",    EVENT_BUFWIPEOUT},
  5542.     {"BufWrite",    EVENT_BUFWRITEPRE},
  5543.     {"BufWritePost",    EVENT_BUFWRITEPOST},
  5544.     {"BufWritePre",    EVENT_BUFWRITEPRE},
  5545.     {"BufWriteCmd",    EVENT_BUFWRITECMD},
  5546.     {"CmdwinEnter",    EVENT_CMDWINENTER},
  5547.     {"CmdwinLeave",    EVENT_CMDWINLEAVE},
  5548.     {"EncodingChanged",    EVENT_ENCODINGCHANGED},
  5549.     {"FileEncoding",    EVENT_ENCODINGCHANGED},
  5550.     {"CursorHold",    EVENT_CURSORHOLD},
  5551.     {"FileAppendPost",    EVENT_FILEAPPENDPOST},
  5552.     {"FileAppendPre",    EVENT_FILEAPPENDPRE},
  5553.     {"FileAppendCmd",    EVENT_FILEAPPENDCMD},
  5554.     {"FileChangedShell",EVENT_FILECHANGEDSHELL},
  5555.     {"FileChangedRO",    EVENT_FILECHANGEDRO},
  5556.     {"FileReadPost",    EVENT_FILEREADPOST},
  5557.     {"FileReadPre",    EVENT_FILEREADPRE},
  5558.     {"FileReadCmd",    EVENT_FILEREADCMD},
  5559.     {"FileType",    EVENT_FILETYPE},
  5560.     {"FileWritePost",    EVENT_FILEWRITEPOST},
  5561.     {"FileWritePre",    EVENT_FILEWRITEPRE},
  5562.     {"FileWriteCmd",    EVENT_FILEWRITECMD},
  5563.     {"FilterReadPost",    EVENT_FILTERREADPOST},
  5564.     {"FilterReadPre",    EVENT_FILTERREADPRE},
  5565.     {"FilterWritePost",    EVENT_FILTERWRITEPOST},
  5566.     {"FilterWritePre",    EVENT_FILTERWRITEPRE},
  5567.     {"FocusGained",    EVENT_FOCUSGAINED},
  5568.     {"FocusLost",    EVENT_FOCUSLOST},
  5569.     {"FuncUndefined",    EVENT_FUNCUNDEFINED},
  5570.     {"GUIEnter",    EVENT_GUIENTER},
  5571.     {"RemoteReply",    EVENT_REMOTEREPLY},
  5572.     {"StdinReadPost",    EVENT_STDINREADPOST},
  5573.     {"StdinReadPre",    EVENT_STDINREADPRE},
  5574.     {"Syntax",        EVENT_SYNTAX},
  5575.     {"TermChanged",    EVENT_TERMCHANGED},
  5576.     {"TermResponse",    EVENT_TERMRESPONSE},
  5577.     {"User",        EVENT_USER},
  5578.     {"VimEnter",    EVENT_VIMENTER},
  5579.     {"VimLeave",    EVENT_VIMLEAVE},
  5580.     {"VimLeavePre",    EVENT_VIMLEAVEPRE},
  5581.     {"WinEnter",    EVENT_WINENTER},
  5582.     {"WinLeave",    EVENT_WINLEAVE},
  5583.     {NULL,        (EVENT_T)0}
  5584. };
  5585.  
  5586. static AutoPat *first_autopat[NUM_EVENTS] =
  5587. {
  5588.     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  5589.     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  5590.     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  5591.     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  5592.     NULL, NULL, NULL, NULL, NULL, NULL, NULL
  5593. };
  5594.  
  5595. /*
  5596.  * struct used to keep status while executing autocommands for an event.
  5597.  */
  5598. typedef struct AutoPatCmd
  5599. {
  5600.     AutoPat    *curpat;    /* next AutoPat to examine */
  5601.     AutoCmd    *nextcmd;    /* next AutoCmd to execute */
  5602.     int        group;        /* group being used */
  5603.     char_u    *fname;        /* fname to match with */
  5604.     char_u    *sfname;    /* sfname to match with */
  5605.     char_u    *tail;        /* tail of fname */
  5606.     EVENT_T    event;        /* current event */
  5607. } AutoPatCmd;
  5608.  
  5609. /*
  5610.  * augroups stores a list of autocmd group names.
  5611.  */
  5612. garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
  5613. #define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
  5614.  
  5615. /*
  5616.  * The ID of the current group.  Group 0 is the default one.
  5617.  */
  5618. #define AUGROUP_DEFAULT        -1        /* default autocmd group */
  5619. #define AUGROUP_ERROR        -2        /* errornouse autocmd group */
  5620. #define AUGROUP_ALL        -3        /* all autocmd groups */
  5621. static int current_augroup = AUGROUP_DEFAULT;
  5622.  
  5623. static int au_need_clean = FALSE;   /* need to delete marked patterns */
  5624.  
  5625. static void show_autocmd __ARGS((AutoPat *ap, EVENT_T event));
  5626. static void au_remove_pat __ARGS((AutoPat *ap));
  5627. static void au_remove_cmds __ARGS((AutoPat *ap));
  5628. static void au_cleanup __ARGS((void));
  5629. static int au_new_group __ARGS((char_u *name));
  5630. static void au_del_group __ARGS((char_u *name));
  5631. static int au_find_group __ARGS((char_u *name));
  5632. static EVENT_T event_name2nr __ARGS((char_u *start, char_u **end));
  5633. static char_u *event_nr2name __ARGS((EVENT_T event));
  5634. static char_u *find_end_event __ARGS((char_u *arg));
  5635. static int event_ignored __ARGS((EVENT_T event));
  5636. static int au_get_grouparg __ARGS((char_u **argp));
  5637. static int do_autocmd_event __ARGS((EVENT_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
  5638. static char_u *getnextac __ARGS((int c, void *cookie, int indent));
  5639. static int apply_autocmds_group __ARGS((EVENT_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap));
  5640. static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
  5641.  
  5642. static EVENT_T    last_event;
  5643. static int    last_group;
  5644.  
  5645. /*
  5646.  * Show the autocommands for one AutoPat.
  5647.  */
  5648.     static void
  5649. show_autocmd(ap, event)
  5650.     AutoPat    *ap;
  5651.     EVENT_T    event;
  5652. {
  5653.     AutoCmd *ac;
  5654.  
  5655.     /* Check for "got_int" (here and at various places below), which is set
  5656.      * when "q" has been hit for the "--more--" prompt */
  5657.     if (got_int)
  5658.     return;
  5659.     if (ap->pat == NULL)        /* pattern has been removed */
  5660.     return;
  5661.  
  5662.     msg_putchar('\n');
  5663.     if (got_int)
  5664.     return;
  5665.     if (event != last_event || ap->group != last_group)
  5666.     {
  5667.     if (ap->group != AUGROUP_DEFAULT)
  5668.     {
  5669.         if (AUGROUP_NAME(ap->group) == NULL)
  5670.         msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
  5671.         else
  5672.         msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
  5673.         msg_puts((char_u *)"  ");
  5674.     }
  5675.     msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
  5676.     last_event = event;
  5677.     last_group = ap->group;
  5678.     msg_putchar('\n');
  5679.     if (got_int)
  5680.         return;
  5681.     }
  5682.     msg_col = 4;
  5683.     msg_outtrans(ap->pat);
  5684.  
  5685.     for (ac = ap->cmds; ac != NULL; ac = ac->next)
  5686.     {
  5687.     if (ac->cmd != NULL)        /* skip removed commands */
  5688.     {
  5689.         if (msg_col >= 14)
  5690.         msg_putchar('\n');
  5691.         msg_col = 14;
  5692.         if (got_int)
  5693.         return;
  5694.         msg_outtrans(ac->cmd);
  5695.         if (got_int)
  5696.         return;
  5697.         if (ac->next != NULL)
  5698.         {
  5699.         msg_putchar('\n');
  5700.         if (got_int)
  5701.             return;
  5702.         }
  5703.     }
  5704.     }
  5705. }
  5706.  
  5707. /*
  5708.  * Mark an autocommand pattern for deletion.
  5709.  */
  5710.     static void
  5711. au_remove_pat(ap)
  5712.     AutoPat *ap;
  5713. {
  5714.     vim_free(ap->pat);
  5715.     ap->pat = NULL;
  5716.     au_need_clean = TRUE;
  5717. }
  5718.  
  5719. /*
  5720.  * Mark all commands for a pattern for deletion.
  5721.  */
  5722.     static void
  5723. au_remove_cmds(ap)
  5724.     AutoPat *ap;
  5725. {
  5726.     AutoCmd *ac;
  5727.  
  5728.     for (ac = ap->cmds; ac != NULL; ac = ac->next)
  5729.     {
  5730.     vim_free(ac->cmd);
  5731.     ac->cmd = NULL;
  5732.     }
  5733.     au_need_clean = TRUE;
  5734. }
  5735.  
  5736. /*
  5737.  * Cleanup autocommands and patterns that have been deleted.
  5738.  * This is only done when not executing autocommands.
  5739.  */
  5740.     static void
  5741. au_cleanup()
  5742. {
  5743.     AutoPat    *ap, **prev_ap;
  5744.     AutoCmd    *ac, **prev_ac;
  5745.     EVENT_T    event;
  5746.  
  5747.     if (autocmd_busy || !au_need_clean)
  5748.     return;
  5749.  
  5750.     /* loop over all events */
  5751.     for (event = (EVENT_T)0; (int)event < (int)NUM_EVENTS;
  5752.                         event = (EVENT_T)((int)event + 1))
  5753.     {
  5754.     /* loop over all autocommand patterns */
  5755.     prev_ap = &(first_autopat[(int)event]);
  5756.     for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
  5757.     {
  5758.         /* loop over all commands for this pattern */
  5759.         prev_ac = &(ap->cmds);
  5760.         for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
  5761.         {
  5762.         /* remove the command if the pattern is to be deleted or when
  5763.          * the command has been marked for deletion */
  5764.         if (ap->pat == NULL || ac->cmd == NULL)
  5765.         {
  5766.             *prev_ac = ac->next;
  5767.             vim_free(ac->cmd);
  5768.             vim_free(ac);
  5769.         }
  5770.         else
  5771.             prev_ac = &(ac->next);
  5772.         }
  5773.  
  5774.         /* remove the pattern if it has been marked for deletion */
  5775.         if (ap->pat == NULL)
  5776.         {
  5777.         *prev_ap = ap->next;
  5778.         vim_free(ap->reg_pat);
  5779.         vim_free(ap);
  5780.         }
  5781.         else
  5782.         prev_ap = &(ap->next);
  5783.     }
  5784.     }
  5785.  
  5786.     au_need_clean = FALSE;
  5787. }
  5788.  
  5789. /*
  5790.  * Add an autocmd group name.
  5791.  * Return it's ID.  Returns AUGROUP_ERROR (< 0) for error.
  5792.  */
  5793.     static int
  5794. au_new_group(name)
  5795.     char_u    *name;
  5796. {
  5797.     int        i;
  5798.  
  5799.     i = au_find_group(name);
  5800.     if (i == AUGROUP_ERROR)    /* the group doesn't exist yet, add it */
  5801.     {
  5802.     /* First try using a free entry. */
  5803.     for (i = 0; i < augroups.ga_len; ++i)
  5804.         if (AUGROUP_NAME(i) == NULL)
  5805.         break;
  5806.     if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
  5807.         return AUGROUP_ERROR;
  5808.  
  5809.     AUGROUP_NAME(i) = vim_strsave(name);
  5810.     if (AUGROUP_NAME(i) == NULL)
  5811.         return AUGROUP_ERROR;
  5812.     if (i == augroups.ga_len)
  5813.     {
  5814.         ++augroups.ga_len;
  5815.         --augroups.ga_room;
  5816.     }
  5817.     }
  5818.  
  5819.     return i;
  5820. }
  5821.  
  5822.     static void
  5823. au_del_group(name)
  5824.     char_u    *name;
  5825. {
  5826.     int        i;
  5827.  
  5828.     i = au_find_group(name);
  5829.     if (i == AUGROUP_ERROR)    /* the group doesn't exist */
  5830.     EMSG2(_("E367: No such group: \"%s\""), name);
  5831.     else
  5832.     {
  5833.     vim_free(AUGROUP_NAME(i));
  5834.     AUGROUP_NAME(i) = NULL;
  5835.     }
  5836. }
  5837.  
  5838. /*
  5839.  * Find the ID of an autocmd group name.
  5840.  * Return it's ID.  Returns AUGROUP_ERROR (< 0) for error.
  5841.  */
  5842.     static int
  5843. au_find_group(name)
  5844.     char_u    *name;
  5845. {
  5846.     int        i;
  5847.  
  5848.     for (i = 0; i < augroups.ga_len; ++i)
  5849.     if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
  5850.         return i;
  5851.     return AUGROUP_ERROR;
  5852. }
  5853.  
  5854. /*
  5855.  * ":augroup {name}".
  5856.  */
  5857.     void
  5858. do_augroup(arg, del_group)
  5859.     char_u    *arg;
  5860.     int        del_group;
  5861. {
  5862.     int        i;
  5863.  
  5864.     if (del_group)
  5865.     {
  5866.     if (*arg == NUL)
  5867.         EMSG(_(e_argreq));
  5868.     else
  5869.         au_del_group(arg);
  5870.     }
  5871.     else if (STRICMP(arg, "end") == 0)   /* ":aug end": back to group 0 */
  5872.     current_augroup = AUGROUP_DEFAULT;
  5873.     else if (*arg)            /* ":aug xxx": switch to group xxx */
  5874.     {
  5875.     i = au_new_group(arg);
  5876.     if (i != AUGROUP_ERROR)
  5877.         current_augroup = i;
  5878.     }
  5879.     else                /* ":aug": list the group names */
  5880.     {
  5881.     msg_start();
  5882.     for (i = 0; i < augroups.ga_len; ++i)
  5883.     {
  5884.         if (AUGROUP_NAME(i) != NULL)
  5885.         {
  5886.         msg_puts(AUGROUP_NAME(i));
  5887.         msg_puts((char_u *)"  ");
  5888.         }
  5889.     }
  5890.     msg_clr_eos();
  5891.     msg_end();
  5892.     }
  5893. }
  5894.  
  5895. /*
  5896.  * Return the event number for event name "start".
  5897.  * Return NUM_EVENTS if the event name was not found.
  5898.  * Return a pointer to the next event name in "end".
  5899.  */
  5900.     static EVENT_T
  5901. event_name2nr(start, end)
  5902.     char_u  *start;
  5903.     char_u  **end;
  5904. {
  5905.     char_u    *p;
  5906.     int        i;
  5907.     int        len;
  5908.  
  5909.     /* the event name ends with end of line, a blank or a comma */
  5910.     for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
  5911.     ;
  5912.     for (i = 0; event_names[i].name != NULL; ++i)
  5913.     {
  5914.     len = (int)STRLEN(event_names[i].name);
  5915.     if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
  5916.         break;
  5917.     }
  5918.     if (*p == ',')
  5919.     ++p;
  5920.     *end = p;
  5921.     if (event_names[i].name == NULL)
  5922.     return NUM_EVENTS;
  5923.     return event_names[i].event;
  5924. }
  5925.  
  5926. /*
  5927.  * Return the name for event "event".
  5928.  */
  5929.     static char_u *
  5930. event_nr2name(event)
  5931.     EVENT_T    event;
  5932. {
  5933.     int        i;
  5934.  
  5935.     for (i = 0; event_names[i].name != NULL; ++i)
  5936.     if (event_names[i].event == event)
  5937.         return (char_u *)event_names[i].name;
  5938.     return (char_u *)"Unknown";
  5939. }
  5940.  
  5941. /*
  5942.  * Scan over the events.  "*" stands for all events.
  5943.  */
  5944.     static char_u *
  5945. find_end_event(arg)
  5946.     char_u  *arg;
  5947. {
  5948.     char_u  *pat;
  5949.     char_u  *p;
  5950.  
  5951.     if (*arg == '*')
  5952.     {
  5953.     if (arg[1] && !vim_iswhite(arg[1]))
  5954.     {
  5955.         EMSG2(_("E215: Illegal character after *: %s"), arg);
  5956.         return NULL;
  5957.     }
  5958.     pat = arg + 1;
  5959.     }
  5960.     else
  5961.     {
  5962.     for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
  5963.     {
  5964.         if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
  5965.         {
  5966.         EMSG2(_("E216: No such event: %s"), pat);
  5967.         return NULL;
  5968.         }
  5969.     }
  5970.     }
  5971.     return pat;
  5972. }
  5973.  
  5974. /*
  5975.  * Return TRUE if "event" is included in 'eventignore'.
  5976.  */
  5977.     static int
  5978. event_ignored(event)
  5979.     EVENT_T    event;
  5980. {
  5981.     char_u    *p = p_ei;
  5982.  
  5983.     if (STRICMP(p_ei, "all") == 0)
  5984.     return TRUE;
  5985.  
  5986.     while (*p)
  5987.     if (event_name2nr(p, &p) == event)
  5988.         return TRUE;
  5989.  
  5990.     return FALSE;
  5991. }
  5992.  
  5993. /*
  5994.  * Return OK when the contents of p_ei is valid, FAIL otherwise.
  5995.  */
  5996.     int
  5997. check_ei()
  5998. {
  5999.     char_u    *p = p_ei;
  6000.  
  6001.     if (STRICMP(p_ei, "all") == 0)
  6002.     return OK;
  6003.  
  6004.     while (*p)
  6005.     if (event_name2nr(p, &p) == NUM_EVENTS)
  6006.         return FAIL;
  6007.  
  6008.     return OK;
  6009. }
  6010.  
  6011. /*
  6012.  * do_autocmd() -- implements the :autocmd command.  Can be used in the
  6013.  *  following ways:
  6014.  *
  6015.  * :autocmd <event> <pat> <cmd>        Add <cmd> to the list of commands that
  6016.  *                    will be automatically executed for <event>
  6017.  *                    when editing a file matching <pat>, in
  6018.  *                    the current group.
  6019.  * :autocmd <event> <pat>        Show the auto-commands associated with
  6020.  *                    <event> and <pat>.
  6021.  * :autocmd <event>            Show the auto-commands associated with
  6022.  *                    <event>.
  6023.  * :autocmd                Show all auto-commands.
  6024.  * :autocmd! <event> <pat> <cmd>    Remove all auto-commands associated with
  6025.  *                    <event> and <pat>, and add the command
  6026.  *                    <cmd>, for the current group.
  6027.  * :autocmd! <event> <pat>        Remove all auto-commands associated with
  6028.  *                    <event> and <pat> for the current group.
  6029.  * :autocmd! <event>            Remove all auto-commands associated with
  6030.  *                    <event> for the current group.
  6031.  * :autocmd!                Remove ALL auto-commands for the current
  6032.  *                    group.
  6033.  *
  6034.  *  Multiple events and patterns may be given separated by commas.  Here are
  6035.  *  some examples:
  6036.  * :autocmd bufread,bufenter *.c,*.h    set tw=0 smartindent noic
  6037.  * :autocmd bufleave         *        set tw=79 nosmartindent ic infercase
  6038.  *
  6039.  * :autocmd * *.c        show all autocommands for *.c files.
  6040.  */
  6041.     void
  6042. do_autocmd(arg, forceit)
  6043.     char_u  *arg;
  6044.     int        forceit;
  6045. {
  6046.     char_u    *pat;
  6047.     char_u    *envpat = NULL;
  6048.     char_u    *cmd;
  6049.     EVENT_T    event;
  6050.     int        need_free = FALSE;
  6051.     int        nested = FALSE;
  6052.     int        group;
  6053.  
  6054.     /*
  6055.      * Check for a legal group name.  If not, use AUGROUP_ALL.
  6056.      */
  6057.     group = au_get_grouparg(&arg);
  6058.     if (arg == NULL)        /* out of memory */
  6059.     return;
  6060.  
  6061.     /*
  6062.      * Scan over the events.
  6063.      * If we find an illegal name, return here, don't do anything.
  6064.      */
  6065.     pat = find_end_event(arg);
  6066.     if (pat == NULL)
  6067.     return;
  6068.  
  6069.     /*
  6070.      * Scan over the pattern.  Put a NUL at the end.
  6071.      */
  6072.     pat = skipwhite(pat);
  6073.     cmd = pat;
  6074.     while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
  6075.     cmd++;
  6076.     if (*cmd)
  6077.     *cmd++ = NUL;
  6078.  
  6079.     /* expand environment variables in the pattern */
  6080.     if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
  6081.     {
  6082.     envpat = expand_env_save(pat);
  6083.     if (envpat != NULL)
  6084.         pat = envpat;
  6085.     }
  6086.  
  6087.     /*
  6088.      * Check for "nested" flag.
  6089.      */
  6090.     cmd = skipwhite(cmd);
  6091.     if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
  6092.     {
  6093.     nested = TRUE;
  6094.     cmd = skipwhite(cmd + 6);
  6095.     }
  6096.  
  6097.     /*
  6098.      * Find the start of the commands.
  6099.      * Expand <sfile> in it.
  6100.      */
  6101.     if (*cmd != NUL)
  6102.     {
  6103.     cmd = expand_sfile(cmd);
  6104.     if (cmd == NULL)        /* some error */
  6105.         return;
  6106.     need_free = TRUE;
  6107.     }
  6108.  
  6109.     /*
  6110.      * Print header when showing autocommands.
  6111.      */
  6112.     if (!forceit && *cmd == NUL)
  6113.     {
  6114.     /* Highlight title */
  6115.     MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
  6116.     }
  6117.  
  6118.     /*
  6119.      * Loop over the events.
  6120.      */
  6121.     last_event = (EVENT_T)-1;        /* for listing the event name */
  6122.     last_group = AUGROUP_ERROR;        /* for listing the group name */
  6123.     if (*arg == '*' || *arg == NUL)
  6124.     {
  6125.     for (event = (EVENT_T)0; (int)event < (int)NUM_EVENTS;
  6126.                         event = (EVENT_T)((int)event + 1))
  6127.         if (do_autocmd_event(event, pat,
  6128.                      nested, cmd, forceit, group) == FAIL)
  6129.         break;
  6130.     }
  6131.     else
  6132.     {
  6133.     while (*arg && !vim_iswhite(*arg))
  6134.         if (do_autocmd_event(event_name2nr(arg, &arg), pat,
  6135.                     nested,    cmd, forceit, group) == FAIL)
  6136.         break;
  6137.     }
  6138.  
  6139.     if (need_free)
  6140.     vim_free(cmd);
  6141.     vim_free(envpat);
  6142. }
  6143.  
  6144. /*
  6145.  * Find the group ID in a ":autocmd" or ":doautocmd" argument.
  6146.  * The "argp" argument is advanced to the following argument.
  6147.  *
  6148.  * Returns the group ID, AUGROUP_ERROR for error (out of memory).
  6149.  */
  6150.     static int
  6151. au_get_grouparg(argp)
  6152.     char_u    **argp;
  6153. {
  6154.     char_u    *group_name;
  6155.     char_u    *p;
  6156.     char_u    *arg = *argp;
  6157.     int        group = AUGROUP_ALL;
  6158.  
  6159.     p = skiptowhite(arg);
  6160.     if (p > arg)
  6161.     {
  6162.     group_name = vim_strnsave(arg, (int)(p - arg));
  6163.     if (group_name == NULL)        /* out of memory */
  6164.         return AUGROUP_ERROR;
  6165.     group = au_find_group(group_name);
  6166.     if (group == AUGROUP_ERROR)
  6167.         group = AUGROUP_ALL;    /* no match, use all groups */
  6168.     else
  6169.         *argp = skipwhite(p);    /* match, skip over group name */
  6170.     vim_free(group_name);
  6171.     }
  6172.     return group;
  6173. }
  6174.  
  6175. /*
  6176.  * do_autocmd() for one event.
  6177.  * If *pat == NUL do for all patterns.
  6178.  * If *cmd == NUL show entries.
  6179.  * If forceit == TRUE delete entries.
  6180.  * If group is not AUGROUP_ALL, only use this group.
  6181.  */
  6182.     static int
  6183. do_autocmd_event(event, pat, nested, cmd, forceit, group)
  6184.     EVENT_T    event;
  6185.     char_u    *pat;
  6186.     int        nested;
  6187.     char_u    *cmd;
  6188.     int        forceit;
  6189.     int        group;
  6190. {
  6191.     AutoPat    *ap;
  6192.     AutoPat    **prev_ap;
  6193.     AutoCmd    *ac;
  6194.     AutoCmd    **prev_ac;
  6195.     int        brace_level;
  6196.     char_u    *endpat;
  6197.     int        findgroup;
  6198.     int        allgroups;
  6199.     int        patlen;
  6200.  
  6201.     if (group == AUGROUP_ALL)
  6202.     findgroup = current_augroup;
  6203.     else
  6204.     findgroup = group;
  6205.     allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
  6206.  
  6207.     /*
  6208.      * Show or delete all patterns for an event.
  6209.      */
  6210.     if (*pat == NUL)
  6211.     {
  6212.     for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
  6213.     {
  6214.         if (forceit)  /* delete the AutoPat, if it's in the current group */
  6215.         {
  6216.         if (ap->group == findgroup)
  6217.             au_remove_pat(ap);
  6218.         }
  6219.         else if (group == AUGROUP_ALL || ap->group == group)
  6220.         show_autocmd(ap, event);
  6221.     }
  6222.     }
  6223.  
  6224.     /*
  6225.      * Loop through all the specified patterns.
  6226.      */
  6227.     for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
  6228.     {
  6229.     /*
  6230.      * Find end of the pattern.
  6231.      * Watch out for a comma in braces, like "*.\{obj,o\}".
  6232.      */
  6233.     brace_level = 0;
  6234.     for (endpat = pat; *endpat && (*endpat != ',' || brace_level
  6235.                          || endpat[-1] == '\\'); ++endpat)
  6236.     {
  6237.         if (*endpat == '{')
  6238.         brace_level++;
  6239.         else if (*endpat == '}')
  6240.         brace_level--;
  6241.     }
  6242.     if (pat == endpat)        /* ignore single comma */
  6243.         continue;
  6244.     patlen = (int)(endpat - pat);
  6245.  
  6246.     /*
  6247.      * Find AutoPat entries with this pattern.
  6248.      */
  6249.     prev_ap = &first_autopat[(int)event];
  6250.     while ((ap = *prev_ap) != NULL)
  6251.     {
  6252.         if (ap->pat != NULL)
  6253.         {
  6254.         /* Accept a pattern when:
  6255.          * - a group was specified and it's that group, or a group was
  6256.          *   not specified and it's the current group, or a group was
  6257.          *   not specified and we are listing
  6258.          * - the length of the pattern matches
  6259.          * - the pattern matches
  6260.          */
  6261.         if ((allgroups || ap->group == findgroup)
  6262.             && ap->patlen == patlen
  6263.             && STRNCMP(pat, ap->pat, patlen) == 0)
  6264.         {
  6265.             /*
  6266.              * Remove existing autocommands.
  6267.              * If adding any new autocmd's for this AutoPat, don't
  6268.              * delete the pattern from the autopat list, append to
  6269.              * this list.
  6270.              */
  6271.             if (forceit)
  6272.             {
  6273.             if (*cmd != NUL && ap->next == NULL)
  6274.             {
  6275.                 au_remove_cmds(ap);
  6276.                 break;
  6277.             }
  6278.             au_remove_pat(ap);
  6279.             }
  6280.  
  6281.             /*
  6282.              * Show autocmd's for this autopat
  6283.              */
  6284.             else if (*cmd == NUL)
  6285.             show_autocmd(ap, event);
  6286.  
  6287.             /*
  6288.              * Add autocmd to this autopat, if it's the last one.
  6289.              */
  6290.             else if (ap->next == NULL)
  6291.             break;
  6292.         }
  6293.         }
  6294.         prev_ap = &ap->next;
  6295.     }
  6296.  
  6297.     /*
  6298.      * Add a new command.
  6299.      */
  6300.     if (*cmd != NUL)
  6301.     {
  6302.         /*
  6303.          * If the pattern we want to add a command to does appear at the
  6304.          * end of the list (or not is not in the list at all), add the
  6305.          * pattern at the end of the list.
  6306.          */
  6307.         if (ap == NULL)
  6308.         {
  6309.         ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
  6310.         if (ap == NULL)
  6311.             return FAIL;
  6312.         ap->pat = vim_strnsave(pat, patlen);
  6313.         ap->patlen = patlen;
  6314.         if (ap->pat == NULL)
  6315.         {
  6316.             vim_free(ap);
  6317.             return FAIL;
  6318.         }
  6319.         ap->reg_pat = file_pat_to_reg_pat(pat, endpat,
  6320.                                &ap->allow_dirs, TRUE);
  6321.         if (ap->reg_pat == NULL)
  6322.         {
  6323.             vim_free(ap->pat);
  6324.             vim_free(ap);
  6325.             return FAIL;
  6326.         }
  6327.         ap->cmds = NULL;
  6328.         *prev_ap = ap;
  6329.         ap->next = NULL;
  6330.         if (group == AUGROUP_ALL)
  6331.             ap->group = current_augroup;
  6332.         else
  6333.             ap->group = group;
  6334.         }
  6335.  
  6336.         /*
  6337.          * Add the autocmd at the end of the AutoCmd list.
  6338.          */
  6339.         prev_ac = &(ap->cmds);
  6340.         while ((ac = *prev_ac) != NULL)
  6341.         prev_ac = &ac->next;
  6342.         ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
  6343.         if (ac == NULL)
  6344.         return FAIL;
  6345.         ac->cmd = vim_strsave(cmd);
  6346. #ifdef FEAT_EVAL
  6347.         ac->scriptID = current_SID;
  6348. #endif
  6349.         if (ac->cmd == NULL)
  6350.         {
  6351.         vim_free(ac);
  6352.         return FAIL;
  6353.         }
  6354.         ac->next = NULL;
  6355.         *prev_ac = ac;
  6356.         ac->nested = (event == EVENT_FILECHANGEDSHELL ? FALSE : nested);
  6357.     }
  6358.     }
  6359.  
  6360.     au_cleanup();    /* may really delete removed patterns/commands now */
  6361.     return OK;
  6362. }
  6363.  
  6364. /*
  6365.  * Implementation of ":doautocmd [group] event [fname]".
  6366.  * Return OK for success, FAIL for failure;
  6367.  */
  6368.     int
  6369. do_doautocmd(arg, do_msg)
  6370.     char_u    *arg;
  6371.     int        do_msg;        /* give message for no matching autocmds? */
  6372. {
  6373.     char_u    *fname;
  6374.     int        nothing_done = TRUE;
  6375.     int        group;
  6376.  
  6377.     /*
  6378.      * Check for a legal group name.  If not, use AUGROUP_ALL.
  6379.      */
  6380.     group = au_get_grouparg(&arg);
  6381.     if (arg == NULL)        /* out of memory */
  6382.     return FAIL;
  6383.  
  6384.     if (*arg == '*')
  6385.     {
  6386.     EMSG(_("E217: Can't execute autocommands for ALL events"));
  6387.     return FAIL;
  6388.     }
  6389.  
  6390.     /*
  6391.      * Scan over the events.
  6392.      * If we find an illegal name, return here, don't do anything.
  6393.      */
  6394.     fname = find_end_event(arg);
  6395.     if (fname == NULL)
  6396.     return FAIL;
  6397.  
  6398.     fname = skipwhite(fname);
  6399.  
  6400.     /*
  6401.      * Loop over the events.
  6402.      */
  6403.     while (*arg && !vim_iswhite(*arg))
  6404.     if (apply_autocmds_group(event_name2nr(arg, &arg),
  6405.                       fname, NULL, TRUE, group, curbuf, NULL))
  6406.         nothing_done = FALSE;
  6407.  
  6408.     if (nothing_done && do_msg)
  6409.     MSG(_("No matching autocommands"));
  6410.  
  6411.     return OK;
  6412. }
  6413.  
  6414. /*
  6415.  * ":doautoall": execute autocommands for each loaded buffer.
  6416.  */
  6417.     void
  6418. ex_doautoall(eap)
  6419.     exarg_T    *eap;
  6420. {
  6421.     int        retval;
  6422.     aco_save_T    aco;
  6423.     buf_T    *buf;
  6424.  
  6425.     /*
  6426.      * This is a bit tricky: For some commands curwin->w_buffer needs to be
  6427.      * equal to curbuf, but for some buffers there may not be a window.
  6428.      * So we change the buffer for the current window for a moment.  This
  6429.      * gives problems when the autocommands make changes to the list of
  6430.      * buffers or windows...
  6431.      */
  6432.     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  6433.     {
  6434.     if (curbuf->b_ml.ml_mfp != NULL)
  6435.     {
  6436.         /* find a window for this buffer and save some values */
  6437.         aucmd_prepbuf(&aco, buf);
  6438.  
  6439.         /* execute the autocommands for this buffer */
  6440.         retval = do_doautocmd(eap->arg, FALSE);
  6441.         do_modelines();
  6442.  
  6443.         /* restore the current window */
  6444.         aucmd_restbuf(&aco);
  6445.  
  6446.         /* stop if there is some error or buffer was deleted */
  6447.         if (retval == FAIL || !buf_valid(buf))
  6448.         break;
  6449.     }
  6450.     }
  6451.  
  6452.     check_cursor();        /* just in case lines got deleted */
  6453. }
  6454.  
  6455. /*
  6456.  * Prepare for executing autocommands for (hidden) buffer "buf".
  6457.  * Search a window for the current buffer.  Save the cursor position and
  6458.  * screen offset.
  6459.  * Set "curbuf" and "curwin" to match "buf".
  6460.  */
  6461.     void
  6462. aucmd_prepbuf(aco, buf)
  6463.     aco_save_T    *aco;        /* structure to save values in */
  6464.     buf_T    *buf;        /* new curbuf */
  6465. {
  6466.     win_T    *win;
  6467.  
  6468.     aco->new_curbuf = buf;
  6469.  
  6470.     /* Find a window that is for the new buffer */
  6471.     if (buf == curbuf)        /* be quick when buf is curbuf */
  6472.     win = curwin;
  6473.     else
  6474. #ifdef FEAT_WINDOWS
  6475.     for (win = firstwin; win != NULL; win = win->w_next)
  6476.         if (win->w_buffer == buf)
  6477.         break;
  6478. #else
  6479.     win = NULL;
  6480. #endif
  6481.  
  6482.     /*
  6483.      * Prefer to use an existing window for the buffer, it has the least side
  6484.      * effects (esp. if "buf" is curbuf).
  6485.      * Otherwise, use curwin for "buf".  It might make some items in the
  6486.      * window invalid.  At least save the cursor and topline.
  6487.      */
  6488.     if (win != NULL)
  6489.     {
  6490.     /* there is a window for "buf", make it the curwin */
  6491.     aco->save_curwin = curwin;
  6492.     curwin = win;
  6493.     aco->save_buf = win->w_buffer;
  6494.     aco->new_curwin = win;
  6495.     }
  6496.     else
  6497.     {
  6498.     /* there is no window for "buf", use curwin */
  6499.     aco->save_curwin = NULL;
  6500.     aco->save_buf = curbuf;
  6501.     --curbuf->b_nwindows;
  6502.     curwin->w_buffer = buf;
  6503.     ++buf->b_nwindows;
  6504.  
  6505.     /* save cursor and topline, set them to safe values */
  6506.     aco->save_cursor = curwin->w_cursor;
  6507.     curwin->w_cursor.lnum = 1;
  6508.     curwin->w_cursor.col = 0;
  6509.     aco->save_topline = curwin->w_topline;
  6510.     curwin->w_topline = 1;
  6511. #ifdef FEAT_DIFF
  6512.     aco->save_topfill = curwin->w_topfill;
  6513.     curwin->w_topfill = 0;
  6514. #endif
  6515.     }
  6516.  
  6517.     curbuf = buf;
  6518. }
  6519.  
  6520. /*
  6521.  * Cleanup after executing autocommands for a (hidden) buffer.
  6522.  * Restore the window as it was (if possible).
  6523.  */
  6524.     void
  6525. aucmd_restbuf(aco)
  6526.     aco_save_T    *aco;        /* structure holding saved values */
  6527. {
  6528.     if (aco->save_curwin != NULL)
  6529.     {
  6530.     /* restore curwin */
  6531. #ifdef FEAT_WINDOWS
  6532.     if (win_valid(aco->save_curwin))
  6533. #endif
  6534.     {
  6535.         /* restore the buffer which was previously edited by curwin, if
  6536.          * it's still the same window and it's valid */
  6537.         if (curwin == aco->new_curwin
  6538.             && buf_valid(aco->save_buf)
  6539.             && aco->save_buf->b_ml.ml_mfp != NULL)
  6540.         {
  6541.         --curbuf->b_nwindows;
  6542.         curbuf = aco->save_buf;
  6543.         curwin->w_buffer = curbuf;
  6544.         ++curbuf->b_nwindows;
  6545.         }
  6546.  
  6547.         curwin = aco->save_curwin;
  6548.         curbuf = curwin->w_buffer;
  6549.     }
  6550.     }
  6551.     else
  6552.     {
  6553.     /* restore buffer for curwin if it still exists and is loaded */
  6554.     if (buf_valid(aco->save_buf) && aco->save_buf->b_ml.ml_mfp != NULL)
  6555.     {
  6556.         --curbuf->b_nwindows;
  6557.         curbuf = aco->save_buf;
  6558.         curwin->w_buffer = curbuf;
  6559.         ++curbuf->b_nwindows;
  6560.         curwin->w_cursor = aco->save_cursor;
  6561.         check_cursor();
  6562.         /* check topline < line_count, in case lines got deleted */
  6563.         if (aco->save_topline <= curbuf->b_ml.ml_line_count)
  6564.         {
  6565.         curwin->w_topline = aco->save_topline;
  6566. #ifdef FEAT_DIFF
  6567.         curwin->w_topfill = aco->save_topfill;
  6568. #endif
  6569.         }
  6570.         else
  6571.         {
  6572.         curwin->w_topline = curbuf->b_ml.ml_line_count;
  6573. #ifdef FEAT_DIFF
  6574.         curwin->w_topfill = 0;
  6575. #endif
  6576.         }
  6577.     }
  6578.     }
  6579. }
  6580.  
  6581. static int    autocmd_nested = FALSE;
  6582.  
  6583. /*
  6584.  * Execute autocommands for "event" and file name "fname".
  6585.  * Return TRUE if some commands were executed.
  6586.  */
  6587.     int
  6588. apply_autocmds(event, fname, fname_io, force, buf)
  6589.     EVENT_T    event;
  6590.     char_u    *fname;        /* NULL or empty means use actual file name */
  6591.     char_u    *fname_io;  /* fname to use for <afile> on cmdline */
  6592.     int        force;        /* when TRUE, ignore autocmd_busy */
  6593.     buf_T    *buf;        /* buffer for <abuf> */
  6594. {
  6595.     return apply_autocmds_group(event, fname, fname_io, force,
  6596.                               AUGROUP_ALL, buf, NULL);
  6597. }
  6598.  
  6599. /*
  6600.  * Like apply_autocmds(), but with extra "eap" argument.  This takes care of
  6601.  * setting v:filearg.
  6602.  */
  6603.     static int
  6604. apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
  6605.     EVENT_T    event;
  6606.     char_u    *fname;
  6607.     char_u    *fname_io;
  6608.     int        force;
  6609.     buf_T    *buf;
  6610.     exarg_T    *eap;
  6611. {
  6612.     return apply_autocmds_group(event, fname, fname_io, force,
  6613.                                AUGROUP_ALL, buf, eap);
  6614. }
  6615.  
  6616. #if defined(FEAT_AUTOCMD) || defined(PROTO)
  6617.     int
  6618. has_cursorhold()
  6619. {
  6620.     return (first_autopat[(int)EVENT_CURSORHOLD] != NULL);
  6621. }
  6622. #endif
  6623.  
  6624.     static int
  6625. apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
  6626.     EVENT_T    event;
  6627.     char_u    *fname;        /* NULL or empty means use actual file name */
  6628.     char_u    *fname_io;  /* fname to use for <afile> on cmdline, NULL means
  6629.                    use fname */
  6630.     int        force;        /* when TRUE, ignore autocmd_busy */
  6631.     int        group;        /* group ID, or AUGROUP_ALL */
  6632.     buf_T    *buf;        /* buffer for <abuf> */
  6633.     exarg_T    *eap;        /* command arguments */
  6634. {
  6635.     char_u    *sfname = NULL;    /* short file name */
  6636.     char_u    *tail;
  6637.     int        save_changed;
  6638.     buf_T    *old_curbuf;
  6639.     int        retval = FALSE;
  6640.     char_u    *save_sourcing_name;
  6641.     linenr_T    save_sourcing_lnum;
  6642.     char_u    *save_autocmd_fname;
  6643.     int        save_autocmd_bufnr;
  6644.     char_u    *save_autocmd_match;
  6645.     int        save_autocmd_busy;
  6646.     int        save_autocmd_nested;
  6647.     static int    nesting = 0;
  6648.     AutoPatCmd    patcmd;
  6649.     AutoPat    *ap;
  6650. #ifdef FEAT_EVAL
  6651.     scid_T    save_current_SID;
  6652.     void    *save_funccalp;
  6653.     char_u    *save_cmdarg;
  6654. #endif
  6655.  
  6656.     /*
  6657.      * Quickly return if there are no autocommands for this event.
  6658.      */
  6659.     if (first_autopat[(int)event] == NULL)
  6660.     return retval;
  6661.  
  6662.     /*
  6663.      * When autocommands are busy, new autocommands are only executed when
  6664.      * explicitly enabled with the "nested" flag.
  6665.      */
  6666.     if (autocmd_busy && !(force || autocmd_nested))
  6667.     return retval;
  6668.  
  6669.     /*
  6670.      * Ignore events in 'eventignore'.
  6671.      */
  6672.     if (event_ignored(event))
  6673.     return retval;
  6674.  
  6675.     /*
  6676.      * Allow nesting of autocommands, but restrict the depth, because it's
  6677.      * possible to create an endless loop.
  6678.      */
  6679.     if (nesting == 10)
  6680.     {
  6681.     EMSG(_("E218: autocommand nesting too deep"));
  6682.     return retval;
  6683.     }
  6684.  
  6685.     /*
  6686.      * Check if these autocommands are disabled.  Used when doing ":all" or
  6687.      * ":ball".
  6688.      */
  6689.     if (       (autocmd_no_enter
  6690.         && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
  6691.         || (autocmd_no_leave
  6692.         && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
  6693.     return retval;
  6694.  
  6695.     /*
  6696.      * Save the autocmd_* variables and info about the current buffer.
  6697.      */
  6698.     save_autocmd_fname = autocmd_fname;
  6699.     save_autocmd_bufnr = autocmd_bufnr;
  6700.     save_autocmd_match = autocmd_match;
  6701.     save_autocmd_busy = autocmd_busy;
  6702.     save_autocmd_nested = autocmd_nested;
  6703.     save_changed = curbuf->b_changed;
  6704.     old_curbuf = curbuf;
  6705.  
  6706.     /*
  6707.      * Set the file name to be used for <afile>.
  6708.      */
  6709.     if (fname_io == NULL)
  6710.     {
  6711.     if (fname != NULL && *fname != NUL)
  6712.         autocmd_fname = fname;
  6713.     else if (buf != NULL)
  6714.         autocmd_fname = buf->b_fname;
  6715.     else
  6716.         autocmd_fname = NULL;
  6717.     }
  6718.     else
  6719.     autocmd_fname = fname_io;
  6720.  
  6721.     /*
  6722.      * Set the buffer number to be used for <abuf>.
  6723.      */
  6724.     if (buf == NULL)
  6725.     autocmd_bufnr = 0;
  6726.     else
  6727.     autocmd_bufnr = buf->b_fnum;
  6728.  
  6729.     /*
  6730.      * When the file name is NULL or empty, use the file name of buffer "buf".
  6731.      * Always use the full path of the file name to match with, in case
  6732.      * "allow_dirs" is set.
  6733.      */
  6734.     if (fname == NULL || *fname == NUL)
  6735.     {
  6736.     if (buf == NULL)
  6737.         fname = NULL;
  6738.     else
  6739.     {
  6740. #ifdef FEAT_SYN_HL
  6741.         if (event == EVENT_SYNTAX)
  6742.         fname = buf->b_p_syn;
  6743.         else
  6744. #endif
  6745.         if (event == EVENT_FILETYPE)
  6746.             fname = buf->b_p_ft;
  6747.         else
  6748.         {
  6749.             if (buf->b_sfname != NULL)
  6750.             sfname = vim_strsave(buf->b_sfname);
  6751.             fname = buf->b_ffname;
  6752.         }
  6753.     }
  6754.     if (fname == NULL)
  6755.         fname = (char_u *)"";
  6756.     fname = vim_strsave(fname);    /* make a copy, so we can change it */
  6757.     }
  6758.     else
  6759.     {
  6760.     sfname = vim_strsave(fname);
  6761.     /* Don't try expanding FileType, Syntax or WindowID. */
  6762.     if (event == EVENT_FILETYPE || event == EVENT_SYNTAX
  6763.         || event == EVENT_REMOTEREPLY)
  6764.         fname = vim_strsave(fname);
  6765.     else
  6766.         fname = FullName_save(fname, FALSE);
  6767.     }
  6768.     if (fname == NULL)        /* out of memory */
  6769.     {
  6770.     vim_free(sfname);
  6771.     return FALSE;
  6772.     }
  6773.  
  6774. #ifdef BACKSLASH_IN_FILENAME
  6775.     /*
  6776.      * Replace all backslashes with forward slashes.  This makes the
  6777.      * autocommand patterns portable between Unix and MS-DOS.
  6778.      * Watch out for the Big5 encoding, it has '\' in the trail byte.
  6779.      */
  6780.     {
  6781.     char_u        *p;
  6782.  
  6783.     if (sfname != NULL)
  6784.     {
  6785.         for (p = sfname; *p; ++p)
  6786. # ifdef  FEAT_MBYTE
  6787.         if (enc_dbcs != 0 && (*mb_ptr2len_check)(p) > 1)
  6788.             ++p;
  6789.         else
  6790. # endif
  6791.         if (*p == '\\')
  6792.             *p = '/';
  6793.     }
  6794.     for (p = fname; *p; ++p)
  6795. # ifdef  FEAT_MBYTE
  6796.         if (enc_dbcs != 0 && (*mb_ptr2len_check)(p) > 1)
  6797.         ++p;
  6798.         else
  6799. # endif
  6800.         if (*p == '\\')
  6801.         *p = '/';
  6802.     }
  6803. #endif
  6804.  
  6805. #ifdef VMS
  6806.     /* remove version for correct match */
  6807.     if (sfname != NULL)
  6808.     vms_remove_version(sfname);
  6809.     vms_remove_version(fname);
  6810. #endif
  6811.  
  6812.     /*
  6813.      * Set the name to be used for <amatch>.
  6814.      */
  6815.     autocmd_match = fname;
  6816.  
  6817.  
  6818.     /* Don't redraw while doing auto commands. */
  6819.     ++RedrawingDisabled;
  6820.     save_sourcing_name = sourcing_name;
  6821.     sourcing_name = NULL;    /* don't free this one */
  6822.     save_sourcing_lnum = sourcing_lnum;
  6823.     sourcing_lnum = 0;        /* no line number here */
  6824.  
  6825. #ifdef FEAT_EVAL
  6826.     save_current_SID = current_SID;
  6827.  
  6828.     /* Don't use local function variables, if called from a function */
  6829.     save_funccalp = save_funccal();
  6830. #endif
  6831.  
  6832.     /*
  6833.      * When starting to execute autocommands, save the search patterns.
  6834.      */
  6835.     if (!autocmd_busy)
  6836.     {
  6837.     save_search_patterns();
  6838.     saveRedobuff();
  6839.     did_filetype = keep_filetype;
  6840.     }
  6841.  
  6842.     /*
  6843.      * Note that we are applying autocmds.  Some commands need to know.
  6844.      */
  6845.     autocmd_busy = TRUE;
  6846.     ++nesting;
  6847.  
  6848.     /* Remember that FileType was triggered.  Used for did_filetype(). */
  6849.     if (event == EVENT_FILETYPE)
  6850.     did_filetype = TRUE;
  6851.  
  6852.     tail = gettail(fname);
  6853.  
  6854.     /* Find first autocommand that matches */
  6855.     patcmd.curpat = first_autopat[(int)event];
  6856.     patcmd.nextcmd = NULL;
  6857.     patcmd.group = group;
  6858.     patcmd.fname = fname;
  6859.     patcmd.sfname = sfname;
  6860.     patcmd.tail = tail;
  6861.     patcmd.event = event;
  6862.     auto_next_pat(&patcmd, FALSE);
  6863.  
  6864.     /* found one, start executing the autocommands */
  6865.     if (patcmd.curpat != NULL)
  6866.     {
  6867. #ifdef FEAT_EVAL
  6868.     /* set v:cmdarg (only when there is a matching pattern) */
  6869.     if (eap != NULL)
  6870.         save_cmdarg = set_cmdarg(eap, NULL);
  6871.     else
  6872.         save_cmdarg = NULL;    /* avoid gcc warning */
  6873. #endif
  6874.     retval = TRUE;
  6875.     /* mark the last pattern, to avoid an endless loop when more patterns
  6876.      * are added when executing autocommands */
  6877.     for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
  6878.         ap->last = FALSE;
  6879.     ap->last = TRUE;
  6880.     check_lnums(TRUE);    /* make sure cursor and topline are valid */
  6881.     do_cmdline(NULL, getnextac, (void *)&patcmd,
  6882.                      DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
  6883. #ifdef FEAT_EVAL
  6884.     if (eap != NULL)
  6885.         (void)set_cmdarg(NULL, save_cmdarg);
  6886. #endif
  6887.     }
  6888.  
  6889.     --RedrawingDisabled;
  6890.     autocmd_busy = save_autocmd_busy;
  6891.     autocmd_nested = save_autocmd_nested;
  6892.     vim_free(sourcing_name);
  6893.     sourcing_name = save_sourcing_name;
  6894.     sourcing_lnum = save_sourcing_lnum;
  6895.     autocmd_fname = save_autocmd_fname;
  6896.     autocmd_bufnr = save_autocmd_bufnr;
  6897.     autocmd_match = save_autocmd_match;
  6898. #ifdef FEAT_EVAL
  6899.     current_SID = save_current_SID;
  6900.     restore_funccal(save_funccalp);
  6901. #endif
  6902.     vim_free(fname);
  6903.     vim_free(sfname);
  6904.     --nesting;
  6905.  
  6906.     /*
  6907.      * When stopping to execute autocommands, restore the search patterns and
  6908.      * the redo buffer.
  6909.      */
  6910.     if (!autocmd_busy)
  6911.     {
  6912.     restore_search_patterns();
  6913.     restoreRedobuff();
  6914.     did_filetype = FALSE;
  6915.     }
  6916.  
  6917.     /*
  6918.      * Some events don't set or reset the Changed flag.
  6919.      * Check if still in the same buffer!
  6920.      */
  6921.     if (curbuf == old_curbuf
  6922.         && (event == EVENT_BUFREADPOST
  6923.         || event == EVENT_BUFWRITEPOST
  6924.         || event == EVENT_FILEAPPENDPOST
  6925.         || event == EVENT_VIMLEAVE
  6926.         || event == EVENT_VIMLEAVEPRE))
  6927.     {
  6928. #ifdef FEAT_TITLE
  6929.     if (curbuf->b_changed != save_changed)
  6930.         need_maketitle = TRUE;
  6931. #endif
  6932.     curbuf->b_changed = save_changed;
  6933.     }
  6934.  
  6935.     au_cleanup();    /* may really delete removed patterns/commands now */
  6936.     return retval;
  6937. }
  6938.  
  6939. /*
  6940.  * Find next autocommand pattern that matches.
  6941.  */
  6942.     static void
  6943. auto_next_pat(apc, stop_at_last)
  6944.     AutoPatCmd    *apc;
  6945.     int        stop_at_last;        /* stop when 'last' flag is set */
  6946. {
  6947.     AutoPat    *ap;
  6948.     AutoCmd    *cp;
  6949.     char_u    *name;
  6950.     char    *s;
  6951.  
  6952.     vim_free(sourcing_name);
  6953.     sourcing_name = NULL;
  6954.  
  6955.     for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
  6956.     {
  6957.     apc->curpat = NULL;
  6958.  
  6959.     /* only use a pattern when it has not been removed, has commands and
  6960.      * the group matches */
  6961.     if (ap->pat != NULL && ap->cmds != NULL
  6962.         && (apc->group == AUGROUP_ALL || apc->group == ap->group))
  6963.     {
  6964.         if (match_file_pat(ap->reg_pat, apc->fname, apc->sfname, apc->tail,
  6965.                                   ap->allow_dirs))
  6966.         {
  6967.         name = event_nr2name(apc->event);
  6968.         s = _("%s Auto commands for \"%s\"");
  6969.         sourcing_name = alloc((unsigned)(STRLEN(s)
  6970.                         + STRLEN(name) + ap->patlen + 1));
  6971.         if (sourcing_name != NULL)
  6972.         {
  6973.             sprintf((char *)sourcing_name, s,
  6974.                            (char *)name, (char *)ap->pat);
  6975.             if (p_verbose >= 8)
  6976.             smsg((char_u *)_("Executing %s"), sourcing_name);
  6977.         }
  6978.  
  6979.         apc->curpat = ap;
  6980.         apc->nextcmd = ap->cmds;
  6981.         /* mark last command */
  6982.         for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
  6983.             cp->last = FALSE;
  6984.         cp->last = TRUE;
  6985.         }
  6986.         line_breakcheck();
  6987.         if (apc->curpat != NULL)        /* found a match */
  6988.         break;
  6989.     }
  6990.     if (stop_at_last && ap->last)
  6991.         break;
  6992.     }
  6993. }
  6994.  
  6995. /*
  6996.  * Get next autocommand command.
  6997.  * Called by do_cmdline() to get the next line for ":if".
  6998.  * Returns allocated string, or NULL for end of autocommands.
  6999.  */
  7000. /* ARGSUSED */
  7001.     static char_u *
  7002. getnextac(c, cookie, indent)
  7003.     int        c;            /* not used */
  7004.     void    *cookie;
  7005.     int        indent;        /* not used */
  7006. {
  7007.     AutoPatCmd        *acp = (AutoPatCmd *)cookie;
  7008.     char_u        *retval;
  7009.     AutoCmd        *ac;
  7010.  
  7011.     /* Can be called again after returning the last line. */
  7012.     if (acp->curpat == NULL)
  7013.     return NULL;
  7014.  
  7015.     /* repeat until we find an autocommand to execute */
  7016.     for (;;)
  7017.     {
  7018.     /* skip removed commands */
  7019.     while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
  7020.         if (acp->nextcmd->last)
  7021.         acp->nextcmd = NULL;
  7022.         else
  7023.         acp->nextcmd = acp->nextcmd->next;
  7024.  
  7025.     if (acp->nextcmd != NULL)
  7026.         break;
  7027.  
  7028.     /* at end of commands, find next pattern that matches */
  7029.     if (acp->curpat->last)
  7030.         acp->curpat = NULL;
  7031.     else
  7032.         acp->curpat = acp->curpat->next;
  7033.     if (acp->curpat != NULL)
  7034.         auto_next_pat(acp, TRUE);
  7035.     if (acp->curpat == NULL)
  7036.         return NULL;
  7037.     }
  7038.  
  7039.     ac = acp->nextcmd;
  7040.  
  7041.     if (p_verbose >= 9)
  7042.     {
  7043.     msg_scroll = TRUE;        /* always scroll up, don't overwrite */
  7044.     smsg((char_u *)_("autocommand %s"), ac->cmd);
  7045.     msg_puts((char_u *)"\n");   /* don't overwrite this either */
  7046.     cmdline_row = msg_row;
  7047.     }
  7048.     retval = vim_strsave(ac->cmd);
  7049.     autocmd_nested = ac->nested;
  7050. #ifdef FEAT_EVAL
  7051.     current_SID = ac->scriptID;
  7052. #endif
  7053.     if (ac->last)
  7054.     acp->nextcmd = NULL;
  7055.     else
  7056.     acp->nextcmd = ac->next;
  7057.     return retval;
  7058. }
  7059.  
  7060. #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
  7061. /*
  7062.  * Function given to ExpandGeneric() to obtain the list of autocommand group
  7063.  * names.
  7064.  */
  7065. /*ARGSUSED*/
  7066.     char_u *
  7067. get_augroup_name(xp, idx)
  7068.     expand_T    *xp;
  7069.     int        idx;
  7070. {
  7071.     if (idx == augroups.ga_len)        /* add "END" add the end */
  7072.     return (char_u *)"END";
  7073.     if (idx >= augroups.ga_len)        /* end of list */
  7074.     return NULL;
  7075.     if (AUGROUP_NAME(idx) == NULL)    /* skip deleted entries */
  7076.     return (char_u *)"";
  7077.     return AUGROUP_NAME(idx);        /* return a name */
  7078. }
  7079.  
  7080. static int include_groups = FALSE;
  7081.  
  7082.     char_u  *
  7083. set_context_in_autocmd(xp, arg, doautocmd)
  7084.     expand_T    *xp;
  7085.     char_u    *arg;
  7086.     int        doautocmd;    /* TRUE for :doautocmd, FALSE for :autocmd */
  7087. {
  7088.     char_u    *p;
  7089.     int        group;
  7090.  
  7091.     /* check for a group name, skip it if present */
  7092.     include_groups = FALSE;
  7093.     p = arg;
  7094.     group = au_get_grouparg(&arg);
  7095.     if (group == AUGROUP_ERROR)
  7096.     return NULL;
  7097.     /* If there only is a group name that's what we expand. */
  7098.     if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
  7099.     {
  7100.     arg = p;
  7101.     group = AUGROUP_ALL;
  7102.     }
  7103.  
  7104.     /* skip over event name */
  7105.     for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
  7106.     if (*p == ',')
  7107.         arg = p + 1;
  7108.     if (*p == NUL)
  7109.     {
  7110.     if (group == AUGROUP_ALL)
  7111.         include_groups = TRUE;
  7112.     xp->xp_context = EXPAND_EVENTS;        /* expand event name */
  7113.     xp->xp_pattern = arg;
  7114.     return NULL;
  7115.     }
  7116.  
  7117.     /* skip over pattern */
  7118.     arg = skipwhite(p);
  7119.     while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
  7120.     arg++;
  7121.     if (*arg)
  7122.     return arg;                /* expand (next) command */
  7123.  
  7124.     if (doautocmd)
  7125.     xp->xp_context = EXPAND_FILES;        /* expand file names */
  7126.     else
  7127.     xp->xp_context = EXPAND_NOTHING;    /* pattern is not expanded */
  7128.     return NULL;
  7129. }
  7130.  
  7131. /*
  7132.  * Function given to ExpandGeneric() to obtain the list of event names.
  7133.  */
  7134. /*ARGSUSED*/
  7135.     char_u *
  7136. get_event_name(xp, idx)
  7137.     expand_T    *xp;
  7138.     int        idx;
  7139. {
  7140.     if (idx < augroups.ga_len)        /* First list group names, if wanted */
  7141.     {
  7142.     if (!include_groups || AUGROUP_NAME(idx) == NULL)
  7143.         return (char_u *)"";    /* skip deleted entries */
  7144.     return AUGROUP_NAME(idx);    /* return a name */
  7145.     }
  7146.     return (char_u *)event_names[idx - augroups.ga_len].name;
  7147. }
  7148.  
  7149. #endif    /* FEAT_CMDL_COMPL */
  7150.  
  7151. /*
  7152.  * Return TRUE if an autocommand is defined for "event" and "pattern".
  7153.  * "pattern" can be NULL to accept any pattern.
  7154.  */
  7155.     int
  7156. au_exists(name, name_end, pattern)
  7157.     char_u    *name;
  7158.     char_u    *name_end;
  7159.     char_u    *pattern;
  7160. {
  7161.     char_u    *event_name;
  7162.     char_u    *p;
  7163.     EVENT_T    event;
  7164.     AutoPat    *ap;
  7165.  
  7166.     /* find the index (enum) for the event name */
  7167.     event_name = vim_strnsave(name, (int)(name_end - name));
  7168.     if (event_name == NULL)
  7169.     return FALSE;
  7170.     event = event_name2nr(event_name, &p);
  7171.     vim_free(event_name);
  7172.  
  7173.     /* return FALSE if the event name is not recognized */
  7174.     if (event == NUM_EVENTS)        /* unknown event name */
  7175.     return FALSE;
  7176.  
  7177.     /* Find the first autocommand for this event.
  7178.      * If there isn't any, return FALSE;
  7179.      * If there is one and no pattern given, return TRUE; */
  7180.     ap = first_autopat[(int)event];
  7181.     if (ap == NULL)
  7182.     return FALSE;
  7183.     if (pattern == NULL)
  7184.     return TRUE;
  7185.  
  7186.     /* Check if there is an autocommand with the given pattern. */
  7187.     for ( ; ap != NULL; ap = ap->next)
  7188.     /* only use a pattern when it has not been removed and has commands */
  7189.     if (ap->pat != NULL && ap->cmds != NULL
  7190.                        && fnamecmp(ap->pat, pattern) == 0)
  7191.         return TRUE;
  7192.  
  7193.     return FALSE;
  7194. }
  7195. #endif    /* FEAT_AUTOCMD */
  7196.  
  7197. #if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
  7198. /*
  7199.  * Try matching a filename with a pattern.
  7200.  * Used for autocommands and 'wildignore'.
  7201.  * Returns TRUE if there is a match, FALSE otherwise.
  7202.  */
  7203.     int
  7204. match_file_pat(pattern, fname, sfname, tail, allow_dirs)
  7205.     char_u    *pattern;        /* pattern to match with */
  7206.     char_u    *fname;            /* full path of file name */
  7207.     char_u    *sfname;        /* short file name or NULL */
  7208.     char_u    *tail;            /* tail of path */
  7209.     int        allow_dirs;        /* allow matching with dir */
  7210. {
  7211.     regmatch_T    regmatch;
  7212.     int        result = FALSE;
  7213. #ifdef FEAT_OSFILETYPE
  7214.     int        no_pattern = FALSE; /* TRUE if check is filetype only */
  7215.     char_u    *type_start;
  7216.     char_u    c;
  7217.     int        match = FALSE;
  7218. #endif
  7219.  
  7220. #ifdef CASE_INSENSITIVE_FILENAME
  7221.     regmatch.rm_ic = TRUE;        /* Always ignore case */
  7222. #else
  7223.     regmatch.rm_ic = FALSE;        /* Don't ever ignore case */
  7224. #endif
  7225. #ifdef FEAT_OSFILETYPE
  7226.     if (*pattern == '<')
  7227.     {
  7228.     /* There is a filetype condition specified with this pattern.
  7229.      * Check the filetype matches first. If not, don't bother with the
  7230.      * pattern (set regprog to NULL).
  7231.      * Always use magic for the regexp.
  7232.      */
  7233.  
  7234.     for (type_start = pattern + 1; (c = *pattern); pattern++)
  7235.     {
  7236.         if ((c == ';' || c == '>') && match == FALSE)
  7237.         {
  7238.         *pattern = NUL;        /* Terminate the string */
  7239.         match = mch_check_filetype(fname, type_start);
  7240.         *pattern = c;        /* Restore the terminator */
  7241.         type_start = pattern + 1;
  7242.         }
  7243.         if (c == '>')
  7244.         break;
  7245.     }
  7246.  
  7247.     /* (c should never be NUL, but check anyway) */
  7248.     if (match == FALSE || c == NUL)
  7249.         regmatch.regprog = NULL;    /* Doesn't match - don't check pat. */
  7250.     else if (*pattern == NUL)
  7251.     {
  7252.         regmatch.regprog = NULL;    /* Vim will try to free regprog later */
  7253.         no_pattern = TRUE;    /* Always matches - don't check pat. */
  7254.     }
  7255.     else
  7256.         regmatch.regprog = vim_regcomp(pattern + 1, TRUE);
  7257.     }
  7258.     else
  7259. #endif
  7260.     regmatch.regprog = vim_regcomp(pattern, TRUE);
  7261.  
  7262.     /*
  7263.      * Try for a match with the pattern with:
  7264.      * 1. the full file name, when the pattern has a '/'.
  7265.      * 2. the short file name, when the pattern has a '/'.
  7266.      * 3. the tail of the file name, when the pattern has no '/'.
  7267.      */
  7268.     if (
  7269. #ifdef FEAT_OSFILETYPE
  7270.         /* If the check is for a filetype only and we don't care
  7271.          * about the path then skip all the regexp stuff.
  7272.          */
  7273.         no_pattern ||
  7274. #endif
  7275.         (regmatch.regprog != NULL
  7276.          && ((allow_dirs
  7277.              && (vim_regexec(®match, fname, (colnr_T)0)
  7278.              || (sfname != NULL
  7279.                  && vim_regexec(®match, sfname, (colnr_T)0))))
  7280.          || (!allow_dirs && vim_regexec(®match, tail, (colnr_T)0)))))
  7281.     result = TRUE;
  7282.  
  7283.     vim_free(regmatch.regprog);
  7284.     return result;
  7285. }
  7286. #endif
  7287.  
  7288. #if defined(FEAT_WILDIGN) || defined(PROTO)
  7289. /*
  7290.  * Return TRUE if a file matches with a pattern in "list".
  7291.  * "list" is a comma-separated list of patterns, like 'wildignore'.
  7292.  * "sfname" is the short file name or NULL, "ffname" the long file name.
  7293.  */
  7294.     int
  7295. match_file_list(list, sfname, ffname)
  7296.     char_u    *list;
  7297.     char_u    *sfname;
  7298.     char_u    *ffname;
  7299. {
  7300.     char_u    buf[100];
  7301.     char_u    *tail;
  7302.     char_u    *regpat;
  7303.     char    allow_dirs;
  7304.     int        match;
  7305.     char_u    *p;
  7306.  
  7307.     tail = gettail(sfname);
  7308.  
  7309.     /* try all patterns in 'wildignore' */
  7310.     p = list;
  7311.     while (*p)
  7312.     {
  7313.     copy_option_part(&p, buf, 100, ",");
  7314.     regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
  7315.     if (regpat == NULL)
  7316.         break;
  7317.     match = match_file_pat(regpat, ffname, sfname, tail, (int)allow_dirs);
  7318.     vim_free(regpat);
  7319.     if (match)
  7320.         return TRUE;
  7321.     }
  7322.     return FALSE;
  7323. }
  7324. #endif
  7325.  
  7326. /*
  7327.  * Convert the given pattern "pat" which has shell style wildcards in it, into
  7328.  * a regular expression, and return the result in allocated memory.  If there
  7329.  * is a directory path separator to be matched, then TRUE is put in
  7330.  * allow_dirs, otherwise FALSE is put there -- webb.
  7331.  * Handle backslashes before special characters, like "\*" and "\ ".
  7332.  *
  7333.  * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
  7334.  * '<html>myfile' becomes '<html>^myfile$' -- leonard.
  7335.  *
  7336.  * Returns NULL when out of memory.
  7337.  */
  7338. /*ARGSUSED*/
  7339.     char_u *
  7340. file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
  7341.     char_u    *pat;
  7342.     char_u    *pat_end;    /* first char after pattern or NULL */
  7343.     char    *allow_dirs;    /* Result passed back out in here */
  7344.     int        no_bslash;    /* Don't use a backward slash as pathsep */
  7345. {
  7346.     int        size;
  7347.     char_u    *endp;
  7348.     char_u    *reg_pat;
  7349.     char_u    *p;
  7350.     int        i;
  7351.     int        nested = 0;
  7352.     int        add_dollar = TRUE;
  7353. #ifdef FEAT_OSFILETYPE
  7354.     int        check_length = 0;
  7355. #endif
  7356.  
  7357.     if (allow_dirs != NULL)
  7358.     *allow_dirs = FALSE;
  7359.     if (pat_end == NULL)
  7360.     pat_end = pat + STRLEN(pat);
  7361.  
  7362. #ifdef FEAT_OSFILETYPE
  7363.     /* Find out how much of the string is the filetype check */
  7364.     if (*pat == '<')
  7365.     {
  7366.     /* Count chars until the next '>' */
  7367.     for (p = pat + 1; p < pat_end && *p != '>'; p++)
  7368.         ;
  7369.     if (p < pat_end)
  7370.     {
  7371.         /* Pattern is of the form <.*>.*  */
  7372.         check_length = p - pat + 1;
  7373.         if (p + 1 >= pat_end)
  7374.         {
  7375.         /* The 'pattern' is a filetype check ONLY */
  7376.         reg_pat = (char_u *)alloc(check_length + 1);
  7377.         if (reg_pat != NULL)
  7378.         {
  7379.             mch_memmove(reg_pat, pat, check_length);
  7380.             reg_pat[check_length] = NUL;
  7381.         }
  7382.         return reg_pat;
  7383.         }
  7384.     }
  7385.     /* else: there was no closing '>' - assume it was a normal pattern */
  7386.  
  7387.     }
  7388.     pat += check_length;
  7389.     size = 2 + check_length;
  7390. #else
  7391.     size = 2;        /* '^' at start, '$' at end */
  7392. #endif
  7393.  
  7394.     for (p = pat; p < pat_end; p++)
  7395.     {
  7396.     switch (*p)
  7397.     {
  7398.         case '*':
  7399.         case '.':
  7400.         case ',':
  7401.         case '{':
  7402.         case '}':
  7403.         case '~':
  7404.         size += 2;    /* extra backslash */
  7405.         break;
  7406. #ifdef BACKSLASH_IN_FILENAME
  7407.         case '\\':
  7408.         case '/':
  7409.         size += 4;    /* could become "[\/]" */
  7410.         break;
  7411. #endif
  7412.         default:
  7413.         size++;
  7414. # ifdef  FEAT_MBYTE
  7415.         if (enc_dbcs != 0 && (*mb_ptr2len_check)(p) > 1)
  7416.         {
  7417.             ++p;
  7418.             ++size;
  7419.         }
  7420. # endif
  7421.         break;
  7422.     }
  7423.     }
  7424.     reg_pat = alloc(size + 1);
  7425.     if (reg_pat == NULL)
  7426.     return NULL;
  7427.  
  7428. #ifdef FEAT_OSFILETYPE
  7429.     /* Copy the type check in to the start. */
  7430.     if (check_length)
  7431.     mch_memmove(reg_pat, pat - check_length, check_length);
  7432.     i = check_length;
  7433. #else
  7434.     i = 0;
  7435. #endif
  7436.  
  7437.     if (pat[0] == '*')
  7438.     while (pat[0] == '*' && pat < pat_end - 1)
  7439.         pat++;
  7440.     else
  7441.     reg_pat[i++] = '^';
  7442.     endp = pat_end - 1;
  7443.     if (*endp == '*')
  7444.     {
  7445.     while (endp - pat > 0 && *endp == '*')
  7446.         endp--;
  7447.     add_dollar = FALSE;
  7448.     }
  7449.     for (p = pat; *p && nested >= 0 && p <= endp; p++)
  7450.     {
  7451.     switch (*p)
  7452.     {
  7453.         case '*':
  7454.         reg_pat[i++] = '.';
  7455.         reg_pat[i++] = '*';
  7456.         break;
  7457.         case '.':
  7458. #ifdef RISCOS
  7459.         if (allow_dirs != NULL)
  7460.              *allow_dirs = TRUE;
  7461.         /* FALLTHROUGH */
  7462. #endif
  7463.         case '~':
  7464.         reg_pat[i++] = '\\';
  7465.         reg_pat[i++] = *p;
  7466.         break;
  7467.         case '?':
  7468. #ifdef RISCOS
  7469.         case '#':
  7470. #endif
  7471.         reg_pat[i++] = '.';
  7472.         break;
  7473.         case '\\':
  7474.         if (p[1] == NUL)
  7475.             break;
  7476. #ifdef BACKSLASH_IN_FILENAME
  7477.         if (!no_bslash)
  7478.         {
  7479.             /* translate:
  7480.              * "\x" to "\\x"  e.g., "dir\file"
  7481.              * "\*" to "\\.*" e.g., "dir\*.c"
  7482.              * "\?" to "\\."  e.g., "dir\??.c"
  7483.              * "\+" to "\+"   e.g., "fileX\+.c"
  7484.              */
  7485.             if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
  7486.                 && p[1] != '+')
  7487.             {
  7488.             reg_pat[i++] = '[';
  7489.             reg_pat[i++] = '\\';
  7490.             reg_pat[i++] = '/';
  7491.             reg_pat[i++] = ']';
  7492.             if (allow_dirs != NULL)
  7493.                 *allow_dirs = TRUE;
  7494.             break;
  7495.             }
  7496.         }
  7497. #endif
  7498.         if (*++p == '?'
  7499. #ifdef BACKSLASH_IN_FILENAME
  7500.             && no_bslash
  7501. #endif
  7502.             )
  7503.             reg_pat[i++] = '?';
  7504.         else
  7505.             if (*p == ',')
  7506.             reg_pat[i++] = ',';
  7507.             else
  7508.             {
  7509.             if (allow_dirs != NULL && vim_ispathsep(*p)
  7510. #ifdef BACKSLASH_IN_FILENAME
  7511.                 && (!no_bslash || *p != '\\')
  7512. #endif
  7513.                 )
  7514.                 *allow_dirs = TRUE;
  7515.             reg_pat[i++] = '\\';
  7516.             reg_pat[i++] = *p;
  7517.             }
  7518.         break;
  7519. #ifdef BACKSLASH_IN_FILENAME
  7520.         case '/':
  7521.         reg_pat[i++] = '[';
  7522.         reg_pat[i++] = '\\';
  7523.         reg_pat[i++] = '/';
  7524.         reg_pat[i++] = ']';
  7525.         if (allow_dirs != NULL)
  7526.             *allow_dirs = TRUE;
  7527.         break;
  7528. #endif
  7529.         case '{':
  7530.         reg_pat[i++] = '\\';
  7531.         reg_pat[i++] = '(';
  7532.         nested++;
  7533.         break;
  7534.         case '}':
  7535.         reg_pat[i++] = '\\';
  7536.         reg_pat[i++] = ')';
  7537.         --nested;
  7538.         break;
  7539.         case ',':
  7540.         if (nested)
  7541.         {
  7542.             reg_pat[i++] = '\\';
  7543.             reg_pat[i++] = '|';
  7544.         }
  7545.         else
  7546.             reg_pat[i++] = ',';
  7547.         break;
  7548.         default:
  7549. # ifdef  FEAT_MBYTE
  7550.         if (enc_dbcs != 0 && (*mb_ptr2len_check)(p) > 1)
  7551.             reg_pat[i++] = *p++;
  7552.         else
  7553. # endif
  7554.         if (allow_dirs != NULL && vim_ispathsep(*p))
  7555.             *allow_dirs = TRUE;
  7556.         reg_pat[i++] = *p;
  7557.         break;
  7558.     }
  7559.     }
  7560.     if (add_dollar)
  7561.     reg_pat[i++] = '$';
  7562.     reg_pat[i] = NUL;
  7563.     if (nested != 0)
  7564.     {
  7565.     if (nested < 0)
  7566.         EMSG(_("E219: Missing {."));
  7567.     else
  7568.         EMSG(_("E220: Missing }."));
  7569.     vim_free(reg_pat);
  7570.     reg_pat = NULL;
  7571.     }
  7572.     return reg_pat;
  7573. }
  7574.